将SetFields与MongoDB C#驱动程序2.0结合使用 [英] Using SetFields with MongoDB C# driver 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
方法(这是Find
和Projection
返回的内容):
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 BsonDocument
s 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屋!