C# 使用c在mongodb中的嵌套数组中选择特定字段

C# 使用c在mongodb中的嵌套数组中选择特定字段,c#,mongodb,mongodb-query,aggregation-framework,mongodb-.net-driver,C#,Mongodb,Mongodb Query,Aggregation Framework,Mongodb .net Driver,我的应用程序使用.NETC驱动程序访问mongodb 我的数据结构如下所示: { "_id" : ObjectId("53d97351e37f520a342e152a"), "Name" : "full question test 2", "keywords" : ["personality", "extraversion", "agreeableness"], "Questions" : [{ "type" : "likert", "text" : "qu

我的应用程序使用.NETC驱动程序访问mongodb

我的数据结构如下所示:

{
 "_id" : ObjectId("53d97351e37f520a342e152a"),
  "Name" : "full question test 2",
  "keywords" : ["personality", "extraversion", "agreeableness"],
   "Questions" : [{
     "type" : "likert",
      "text" : "question 1",
       }, 
       {
      "type" : "likert",
      "text" : "question 2",
      }]
}
db.collection.aggregate([
    { "$match": {
        "Name": "fullquestion test 2"
    }},
    { "$project": {
        "Name": 1,
        "Questions.type": 1
    }}
])
我要做的是只从questions数组中选择type列

这是我现在的linq代码:

from e in collection.AsQueryable<scales>() 
where e.Name == "full question test 2"
select new { e.Id, e.Name, e.Questions}
这将返回所有问题属性(类型和文本)。我只想要那种类型的。我可以这样做,比如说e.Questions[0]。text,e.Questions[1]。text

但是问题的数量因文件而异,所以我喜欢一个不需要手动编码的解决方案


思想开放

此处包装的标准查询方法有一种可用于字段选择的投影形式,但这无法执行诸如在数组元素中选择特定字段之类的操作。至少对于多个字段

但单字段应该可以仅使用点符号形式访问元素:

from e in collection.AsQueryable<scales>() 
where e.Name == "full question test 2"
select new { e.Id, e.Name, e.Questions.type }
或为C构建BSON文档:

var match = new BsonDocument {
    { "$match",new BsonDocument {
           {
                "Name", "full question test 2"
           }
      }
    }
};

var project = new BsonDocument {
    { "$project", new BsonDocument {
          { "Name", 1 },
          { "Questions.type": 1 }         
      }
    }
};

var pipeline = new [] { match, project };
var result = collection.aggregate(pipeline);
本质上,聚合管道的$project阶段可以做的事情远不止选择字段。这里的额外支持允许更改数组中文档的结构


支持将聚合管道映射到Linq是一项正在进行的工作。您可以在此处监视问题:

是否确定不使用w.r.t.标准查询方法执行此操作?db.collection.find{Name:fullquestion test 2},{Name:1,Questions.type:1}返回相同的结果。“还是一个C类的东西?”贾斯汀·布莱恩在自动驾驶仪上。单场,所以你是对的,标准投影应该适用于单场。仍在考虑多个领域的术语。感谢您的快速响应!不幸的是,点符号id.Questions.type不起作用:我得到一个错误,显示System.Array不包含“type”的定义@AlexKogan不确定这是否在linq的投影上下文中起作用,并且没有时间启动。但聚合方法确实有效。这只是意味着您不能为此使用linq形成查询。