mongodb 在嵌套数组中获取数组

mongodb getting an array inside a nested array

我还是mongodb的新手,我有这个基本的注册系统数据:

{ "_id" : ObjectId("62277d92a561e550d5ec73ca"), "sid" : 1, "sname" : "sad", "semail" : "dsa", "scourse" : "it", "enrolled" : [ { "subjid" : 3 } ] }
{ "_id" : ObjectId("6227875bdbcc41a56a863697"), "sid" : 2, "sname" : "daws", "semail" : "dws", "scourse" : "cs", "enrolled" : [ { "subjid" : 1, "grades" : [ { "prelim" : "A", "midterm" : "B", "prefinal" : "B", "final" : "A" } ] }, { "subjid" : 2, "grades" : [ { "prelim" : "D", "midterm" : "A", "prefinal" : "B", "final" : "F" } ] } ] }

我想显示已经注册subjid 1的sid 2的成绩

我试过使用这条聚合线:

 db.students2.aggregate( [{"$match":{"sid":{"$eq":2},"enrolled.subjid":{"$eq":2}}}, {$group: {_id:'$enrolled.subjid[1]', prelim:{$first:'$enrolled.grades.prelim'},midterm:{$first:'$enrolled.grades.midterm'},prefinal:{$first:'$enrolled.grades.prefinal'},"final":{$first:'$enrolled.grades.final'} } } ])

但这是结果:

{ "_id" : [ ], "prelim" : [ [ "A" ], [ "D" ] ], "midterm" : [ [ "B" ], [ "A" ] ], "prefinal" : [ [ "B" ], [ "B" ] ], "final" : [ [ "A" ], [ "F" ] ] }

我只想得到subjid 1的成绩但是它也得到了subjid 2的成绩

也许你需要这样的东西:

db.collection.aggregate([
{
 "$match": {
  "sid": 2,
  "enrolled.subjid": 1
 }
},
{
 "$addFields": {
  "enrolled": {
    "$filter": {
      "input": "$enrolled",
      "as": "en",
      "cond": {
        $eq: [
          "$$en.subjid",
          1
        ]
      }
    }
   }
  }
 },
 {
  $unwind: "$enrolled"
 },
 {
  $unwind: "$enrolled.grades"
 },
 {$limit:1}
  ,
 {
  $project: {
  _id: "$enrolled.subjid",
  prelim: "$enrolled.grades.prelim",
  midterm: "$enrolled.grades.midterm",
  prefinal: "$enrolled.grades.prefinal",
  "final": "$enrolled.grades.final"
  }
 }
])

解释:

  1. 匹配必要的文件(sid=2,subjid=1)
  2. 仅根据 subjid ( subjid=1 ) 筛选已注册的元素
  3. 展开两个数组
  4. 仅限第一个结果文档可用,以防有更多文档。
  5. 投影必要的字段

playground