Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I accomplish this with the 2.0 driver?

like image 491
Graeme Avatar asked Sep 28 '22 18:09

Graeme


1 Answers

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))

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))

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)
like image 70
i3arnon Avatar answered Oct 07 '22 20:10

i3arnon