c# mongodb projection builder 通过迭代

c# mongodb projection builder through iteration

我的目标是从字段列表类型构建投影定义。我想动态地实现这一点。当我这样做时它不起作用,

var projectionBuilder = Builders<Article>.Projection;
foreach (var field in requestDetails.Fields)
{
  projectionBuilder.Include(field);
}
await _collection.Find<Entity>(_ => true).Project<Entity>(projectionBuilder.Exclude("_id")).Limit(10).ToListAsync();

这样使用

var projectionDefinition = Builders<DBInfo>.Projection.Include(_ => _.count);
projectionDefinition = projectionDefinition.Include(_ => _.info.x);
projectionDefinition = projectionDefinition.Include("type"); // You can also use text

这里有完整的例子

https://github.com/iso8859/learn-mongodb-by-example/blob/main/dotnet/02%20-%20Intermediate/DynamicQuery.cs