MongoDb:如何使用C#官方驱动程序返回select(find)中的distinct字段(MongoDb: how to return distinct field in select (find) with C# official driver)
我需要从用户集合中选择用户名。 我是这样做的:
MongoCollection<Enums> coll = Db.GetCollection<Enums>("Users"); var query = Query.EQ("_id", id); var res = coll.FindOne(query); var name = res.Name; var url = res.UserUrl; //or some more fields, not just Name假设用户文档可以包含大量数据,并且不需要传输整个用户文档, 那么如何使用官方C#驱动程序只选择几个不同的字段?
I need to select User Name from the collection of Users. I do it in a such way:
MongoCollection<Enums> coll = Db.GetCollection<Enums>("Users"); var query = Query.EQ("_id", id); var res = coll.FindOne(query); var name = res.Name; var url = res.UserUrl; //or some more fields, not just NameAssuming that User document can contain a lot of data, and there is no need to transfer the whole user document, how to select only a few distinct fields, using official C# driver?
最满意答案
您必须使用返回MongoCursor的函数。 在MongoCursor中,您可以指定要返回的字段。
var result = Db.GetCollection<Enums>("Users").FindAll(); result.Fields = Fields.Include(new [] {"Name"});; foreach (var user in result) { Console.WriteLine(user.Name); }You'll have to use a function that returns a MongoCursor. In the MongoCursor you can specify the fields you want to return.
var result = Db.GetCollection<Enums>("Users").FindAll(); result.Fields = Fields.Include(new [] {"Name"});; foreach (var user in result) { Console.WriteLine(user.Name); }更多推荐
发布评论