Using SetFields with MongoDB C# driver 2.0

寵の児 提交于 2019-12-07 04:29:21

问题


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?


回答1:


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)



回答2:


If you want SetFields back you can write your own extension method:

 public static class MongoExtensions
{
    public static IFindFluent<T, T> SetFields<T>(this IFindFluent<T, T> query, params string[] fields)
    {
        if ( fields == null || fields.Length == 0 )
        {
            return query;
        }

        var project = Builders<T>.Projection.IncludeAll<T>(fields);

        return query.Project<T>(project);
    }


    public static ProjectionDefinition<T> IncludeAll<T>(this ProjectionDefinitionBuilder<T> projection,
        params string[] fields)
    {
        ProjectionDefinition<T> project = null;

        foreach (string columnName in fields)
        {
            if (project == null)
            {
                project = Builders<T>.Projection.Include(columnName);
            }
            else
            {
                project = project.Include(columnName);
            }
        }
        return project;

    }
}


来源:https://stackoverflow.com/questions/28541082/using-setfields-with-mongodb-c-sharp-driver-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!