3

当字段以字符串数组的形式给出时,如何在新的 MongoDB C# 驱动程序中投影字段?我可以通过做找到在单个领域进行投影的方法

collection.find(filter).Project(Builders<Category>.Projection.Include(fieldName)

如何扩展它以获取字段数组?

4

3 回答 3

5

还有扩展方法Include

var projection = Builders<Category>.Projection.Include(fieldList.First());
foreach (var field in fieldList.Skip(1))
{
    projection = projection.Include(field);
}
var result = await collection.Find(filter).Project(projection).ToListAsync();
于 2015-07-08T01:49:05.783 回答
0

比 mofenko 更好的方法,您不必包含第一列:

ProjectionDefinition<BsonDocument> project = null;

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

这适用于松散类型的数据。如果您使用类替换BsonDocument为您的类

于 2016-02-29T15:36:25.383 回答
0

另一种方式,假设 fieldList 是一个可枚举的字符串:

var project = Builders<BsonDocument>.Projection.Combine(fieldList.Select(x => Builders<BsonDocument>.Projection.Include(x)).ToList());
于 2018-11-06T14:58:06.477 回答