在 C# 中的多个字段上项目 MongoDB 2.0
Project on multiple fields in C# MongoDB 2.0
当字段以字符串数组的形式给出时,您如何在新的 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);
}
}
这适用于松散类型的数据。如果您使用的是 classes,请将 BsonDocument
替换为您的 class
另一种方式,假设 fieldList 是一个可枚举的字符串:
var project = Builders<BsonDocument>.Projection.Combine(fieldList.Select(x => Builders<BsonDocument>.Projection.Include(x)).ToList());
当字段以字符串数组的形式给出时,您如何在新的 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);
}
}
这适用于松散类型的数据。如果您使用的是 classes,请将 BsonDocument
替换为您的 class
另一种方式,假设 fieldList 是一个可枚举的字符串:
var project = Builders<BsonDocument>.Projection.Combine(fieldList.Select(x => Builders<BsonDocument>.Projection.Include(x)).ToList());