当字段以字符串数组的形式给出时,如何在新的 MongoDB C# 驱动程序中投影字段?我可以通过做找到在单个领域进行投影的方法
collection.find(filter).Project(Builders<Category>.Projection.Include(fieldName)
如何扩展它以获取字段数组?
当字段以字符串数组的形式给出时,如何在新的 MongoDB C# 驱动程序中投影字段?我可以通过做找到在单个领域进行投影的方法
collection.find(filter).Project(Builders<Category>.Projection.Include(fieldName)
如何扩展它以获取字段数组?
还有扩展方法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();
比 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
为您的类
另一种方式,假设 fieldList 是一个可枚举的字符串:
var project = Builders<BsonDocument>.Projection.Combine(fieldList.Select(x => Builders<BsonDocument>.Projection.Include(x)).ToList());