MongoDB的 - 包含或排除用C#驱动程序的某些元素 [英] Mongodb -- include or exclude certain elements with c# driver

查看:463
本文介绍了MongoDB的 - 包含或排除用C#驱动程序的某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何在C#中翻译这蒙戈查询到Query.EQ声明?

  db.users.find({名称:'鲍勃'},{_id:1}​​);

在换句话说,我不想回到了C#的一切 - 只是一个因素,我需要的_id。和往常一样,<一个href=\"http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-FindandFindAsmethods\">Mongo C#驱动教程是没有帮助的。


解决方案

更新:随着新版本的驱动程序(1.6+),就可以避免字段名的硬编码和使用LINQ来代替:

  VAR用户= usersCollection.FindAllAs&LT; T&GT;()
                           .SetFields(领域&LT; T&GT; .INCLUDE(E =&GT; e.Id,E =&GT; e.Name));


您可以通过 SetFields MongoDB的光标的方法做

  VAR用户= usersCollection.FindAllAs&LT; T&GT;()
                 .SetFields(_ ID)//只包括_id
                 .ToList();

默认情况下将 SetFileds 包括指定的字段。如果您需要排除某些字段,你可以使用:

  VAR用户= usersCollection.FindAllAs&LT; T&GT;()
                 .SetFields(Fields.Exclude(_ ID))//排除_id场
                 .ToList();

或者你可以同时使用它们:

  VAR用户= usersCollection.FindAllAs&LT; T&GT;()
                 .SetFields(Fields.Exclude(_ ID)//排除_id场
                                  .INCLUDE(名字))//包括名称字段
                 .ToList();

How would I translate this mongo query to a Query.EQ statement in C#?

db.users.find({name: 'Bob'}, {'_id': 1});

In other words, I don't want everything returned to C# -- Just the one element I need, the _id. As always, the Mongo C# Driver tutorial is not helpful.

解决方案

Update: With new driver version (1.6+) you can avoid fields names hard-coding and use linq instead:

var users = usersCollection.FindAllAs<T>()
                           .SetFields(Fields<T>.Include(e => e.Id, e => e.Name));


You can do it via SetFields method of mongodb cursor:

var users = usersCollection.FindAllAs<T>()
                 .SetFields("_id") // include only _id
                 .ToList();

By defaul SetFileds include specified fields. If you need exclude certain fields you can use:

var users = usersCollection.FindAllAs<T>()
                 .SetFields(Fields.Exclude("_id")) // exclude _id field
                 .ToList();

Or you can use them together:

var users = usersCollection.FindAllAs<T>()
                 .SetFields(Fields.Exclude("_id")   // exclude _id field
                                  .Include("name")) // include name field
                 .ToList();

这篇关于MongoDB的 - 包含或排除用C#驱动程序的某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆