mej*_*vid 7 c# mongodb mongodb-query
我有以下代码,我是mongodb的新手,我需要帮助找到集合中的特定元素.
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
*/
}
}
}
Run Code Online (Sandbox Code Playgroud)
一旦我找到了我想要打印的用户,那是可行的还是只会找回位置?如果是这样,我该如何打印?
我看过一些例子collection.Find(x => x.something),但我不知道x是什么或意思是什么
pie*_*eru 24
要查找记录,您可以在find中使用Lambda,例如:
var results = collection.Find(x => x.name == "system").ToList();
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用使用强类型Lambda或文本的构建器:
var filter = Builders<User>.Filter.Eq(x => x.name, "system")
Run Code Online (Sandbox Code Playgroud)
要么
var filter = Builders<User>.Filter.Eq("name", "system")
Run Code Online (Sandbox Code Playgroud)
然后使用如上所述的find
// 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();
Run Code Online (Sandbox Code Playgroud)