【问题标题】:Project on multiple fields in C# MongoDB 2.0在 C# MongoDB 2.0 中的多个字段上进行项目
【发布时间】:2015-07-07 23:25:16
【问题描述】:

当字段以字符串数组的形式给出时,您如何在新的 MongoDB C# 驱动程序中对字段进行投影? 我可以通过

找到在单个字段上进行投影的方法

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

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

【问题讨论】:

    标签: c# .net mongodb mongodb-.net-driver mongodb-csharp-2.0


    【解决方案1】:

    还有扩展方法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();
    

    【讨论】:

      【解决方案2】:

      比 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 替换为您的课程

      【讨论】:

      • 这样真的更好吗?它有更多的代码行,并为每个包含的字段检查额外的if 条件
      【解决方案3】:

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

      var project = Builders<BsonDocument>.Projection.Combine(fieldList.Select(x => Builders<BsonDocument>.Projection.Include(x)).ToList());
      

      【讨论】:

        猜你喜欢
        • 2018-05-22
        • 2018-06-16
        • 1970-01-01
        • 2019-03-30
        • 2017-06-03
        • 1970-01-01
        • 1970-01-01
        • 2017-04-03
        • 1970-01-01
        相关资源
        最近更新 更多