I have the below code and I am new to mongodb, I need help in finding an specific element in the collection.
using MongoDB.Bson;
using MongoDB.Driver;
namesp
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mongo_console
{
class Program
{
public static void Main(string[] args)
{
MongoClient client = new MongoClient();
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("admin");
MongoCollection<Book> collection = db.GetCollection<Book>("Book");
Book book1 = new Book
{
Id = ObjectId.GenerateNewId(),
name = "Reel To Real"
};
Book book2 = new Book
{
Id = ObjectId.GenerateNewId(),
name = "Life"
};
collection.Save(book1);
collection.Save(book2);
var query = Query<Book>.EQ(u => u.Id, new ObjectId("5a5ee6360222da8ad498f3ff"));
Book list = collection.FindOne(query);
Console.WriteLine( "Book Name " + list.name);
Console.ReadLine();
}
}
public class Book
{
[BsonId]
public ObjectId Id { get; set; }
public string name { get; set; }
public Book()
{
}
public Book(ObjectId id, string name)
{
this.Id = id;
this.name = name;
}
}
}
It also Varies according to the .Net framework version we are using. If we Use 2x driver it should look like :
var list = await collection.Find(new BsonDocument()).ToListAsync();
method 2
await collection.Find(new BsonDocument()).ForEachAsync(X=>Console.WriteLine(X));
Reference Example
To find a record you could use Lambda in find, for example:
var results = collection.Find(x => x.name == "system").ToList();
Alternatively you can use Builders which work with strongly typed Lambda or text:
var filter = Builders<User>.Filter.Eq(x => x.name, "system")
Or
var filter = Builders<User>.Filter.Eq("name", "system")
And then use find as above
// results will be a collection of your documents matching your filter criteria
// Sync syntax
var results = collection.Find(filter).ToList();
// Async syntax
var results = await collection.Find(filter).ToListAsync();