MongoDb:如何使用C#官方驱动程序返回select(find)中的distinct字段(MongoDb: how to return distinct field in select (find

编程入门 行业动态 更新时间:2024-10-10 00:22:47
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 Name

Assuming 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); }

更多推荐

本文发布于:2023-08-07 17:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   如何使用   驱动程序   官方   select

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!