1

Hello I am trying to query my database to get an object. I followed a guide and it seems everyone is just using a foreach on the whole collection, is this how its supposed to be done?

public void asd()
        {
            MongoClient _client = new MongoClient();
            IMongoDatabase _database = _client.GetDatabase("BlogDB");

            IMongoCollection<Blog> collection = _database.GetCollection<Blog>("Blog");

            var filter = new BsonDocument();
            var result = collection.Find(filter)
                 .Project(Blog => Blog.Posts)
                 .ToList();
            foreach (Posts post in result.FirstOrDefault())
            {
                if (post.postid == postid)
                {
                    //Do something with post E.g post.myfunction();
                }
            }
        }

Is there no way to get only the specific post from a query?

I tried to use a filter but collection.Find(filter) still returns a collection with my whole bsondocument.

2 Answers 2

1

How about simplifying code little bit. Since you need single matching document,

Replace

var result = collection.Find(filter)
     .Project(Blog => Blog.Posts)
     .ToList();
foreach (Posts post in result.FirstOrDefault())
{
    if (post.postid == postid)
    {
        //Do something with post E.g post.myfunction();
    }
}

With

var post = collection.Find(filter)
     .Project(Blog => Blog.Posts)
     .Limit(1)
     .FirstOrDefault();
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the following code

public Posts Get(int id)
    {
        var builder = Builders<Posts>.Filter;

        var query = builder.Eq(x => x.postid, id);
        return collection.Find(query).SingleOrDefaultAsync().Result;
    }

1 Comment

How can i return a Posts from collection Blog? If i change my collection to IMongoCollection<Posts> collection = _database.GetCollection<Posts>("Blog"); It compiles but i get null as a reference..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.