MongoDB和C#Find() [英] MongoDB and C# Find()
本文介绍了MongoDB和C#Find()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,并且是mongodb的新手,我需要帮助才能找到集合中的特定元素.
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?
我看过一些示例集合.find(x => x.something)但我不知道x是什么意思
I have seen some examples collection.Find(x => x.something) but I do not know what that x is or mean
推荐答案
要查找记录,可以在查找中使用Lambda,例如:
To find a record you could use Lambda in find, for example:
var results = collection.Find(x => x.name == "system").ToList();
或者,您可以使用适用于强类型Lambda或文本的构建器:
Alternatively you can use Builders which work with strongly typed Lambda or text:
var filter = Builders<User>.Filter.Eq(x => x.name, "system")
或
var filter = Builders<User>.Filter.Eq("name", "system")
然后使用上述查找功能
// 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();
这篇关于MongoDB和C#Find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文