C#MongoDB 2.0中的多字段项目
当字段以字符串数组的形式给出时,如何在新的MongoDB C#驱动程序中对字段进行投影?。 我可以通过这样做找到在单个领域进行项目的方法C#MongoDB 2.0中的多字段项目,c#,.net,mongodb,mongodb-.net-driver,mongodb-csharp-2.0,C#,.net,Mongodb,Mongodb .net Driver,Mongodb Csharp 2.0,当字段以字符串数组的形式给出时,如何在新的MongoDB C#驱动程序中对字段进行投影?。 我可以通过这样做找到在单个领域进行项目的方法 collection.find(filter).Project(Builders.Projection.Include(fieldName) 如何扩展它以获取字段数组?还有扩展方法Include var projection = Builders<Category>.Projection.Include(fieldList.First()); fo
collection.find(filter).Project(Builders.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();
var projection=Builders.projection.Include(fieldList.First());
foreach(字段列表中的变量字段。跳过(1))
{
投影=投影。包括(字段);
}
var result=await collection.Find(filter.Project(projection.toListSync();
一种比mofenko更好的方法,您不必包括第一列:
ProjectionDefinition<BsonDocument> project = null;
foreach (string columnName in columnsToInclude)
{
if (project == null)
{
project = Builders<BsonDocument>.Projection.Include(columnName);
}
else
{
project = project.Include(columnName);
}
}
projectOnDefinition项目=null;
foreach(columnsToInclude中的字符串columnName)
{
如果(项目==null)
{
project=Builders.Projection.Include(columnName);
}
其他的
{
项目=项目。包括(列名称);
}
}
这适用于松散类型的数据。如果您使用类,请用类替换
BsonDocument
,另一种方法,假设fieldList是字符串可枚举的,则为:
var project = Builders<BsonDocument>.Projection.Combine(fieldList.Select(x => Builders<BsonDocument>.Projection.Include(x)).ToList());
var project=Builders.Projection.Combine(fieldList.Select(x=>Builders.Projection.Include(x)).ToList();
这真的更好吗?它有更多的代码行,并检查每个包含字段的附加条件