Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB and C# Find()

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;
namespace mongo_console    {

public class User    {
    public ObjectId Id { get; set; }
    public string name { get; set; }
    public string pwd { get; set; }
}
class Program    {
    static void Main(string[] args)
    {
        MongoClient client = new MongoClient();
        MongoServer server = client.GetServer();
        MongoDatabase db = server.GetDatabase("Users");
        MongoCollection<User> collection = db.GetCollection<User>("users");

        User user = new User
        {
            Id = ObjectId.GenerateNewId(),
            name = "admin",
            pwd = "admin"
        };
        User user2 = new User
        {
            Id = ObjectId.GenerateNewId(),
            name = "system",
            pwd = "system"
        };
        collection.Save(user);
        collection.Save(user2);

        /*
         * How do I collection.Find() for example using the name
         */
  }
}
}

Once I find the user I will like to print it, is that posible or will find only return the position? if so, how do I print it?

I have seen some examples collection.Find(x => x.something) but I do not know what that x is or mean

like image 575
mejia_david Avatar asked Oct 20 '16 21:10

mejia_david


People also ask

Can I use C++ with MongoDB?

Welcome to the documentation site for the official MongoDB C++ driver. You can add the driver to your application to work with MongoDB using the C++11 or later standard.

Can you use MongoDB with C#?

By developing with C# and MongoDB together one opens up a world of possibilities. Console, window, and web applications are all possible. As are cross-platform mobile applications using the Xamarin framework.


1 Answers

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();
like image 64
pieperu Avatar answered Sep 20 '22 14:09

pieperu