将SetFields与MongoDB C#驱动程序2.0一起使用

时间:2015-02-16 12:06:22

标签: c# .net mongodb filtering mongodb-.net-driver

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

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

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

2 个答案:

答案 0 :(得分:4)

您需要在Projection上使用IFindFluent方法(FindProjection返回):

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

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

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

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

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

答案 1 :(得分:0)

如果您想让SetFields返回,您可以编写自己的扩展方法:

 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;

    }
}