Reputation: 381
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.
Upvotes: 1
Views: 2414
Reputation: 9018
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();
Upvotes: 1
Reputation: 994
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;
}
Upvotes: 0