将SetFields与MongoDB C#驱动程序2.0结合使用 [英] Using SetFields with MongoDB C# driver 2.0

查看:168
本文介绍了将SetFields与MongoDB C#驱动程序2.0结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用旧驱动程序,我可以指定要从查询中返回的字段,如下所示:

With the old driver I could specify the fields I wanted to return from a query as follows:

var cursor = Collection.Find(query).
  SetFields(Fields<MealPlan>.Exclude (plan => plan.Meals));

如何使用2.0驱动程序来完成此操作?

How do I accomplish this with the 2.0 driver?

推荐答案

您需要在IFindFluent上使用Projection方法(这是FindProjection返回的内容):

You need to use the Projection method on IFindFluent (which is what Find and Projection return):

var findFluent = Collection.Find(query).Projection(Fields<MealPlan>.Exclude (plan => plan.Meals))

现在,这最终将生成一个BsonDocument s的游标,因为它不知道投影的外观.您可以调用通用Projection来添加该类型:

Now, this would eventually generate a cursor of BsonDocuments since it doesn't know how the projection looks. You can call the generic Projection instead to add that type:

var findFluent = Collection.Find(query).Projection<MealPlan>(Fields<MealPlan>.Exclude (plan => plan.Meals))


从更一般的意义上讲(使用Exclude时不那么相关),您还可以使用lambda表达式指定字段:


In a more general sense (which is less relevant when using Exclude), you could also specify fields using a lambda expression:

var findFluent = Collection.Find(query).Projection(plan => plan.Meals)

这篇关于将SetFields与MongoDB C#驱动程序2.0结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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