简体   繁体   中英

Get object from mongodb c#

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.

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;
    }

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM