查询以从mongodb的对象嵌套数组中获取ID

时间:2020-10-14 12:55:16

标签: mongodb mongodb-query aggregation-framework aggregation

这是数据:

[
  {
    id: 1,
    questions: [{
        questionID: 11,
        createdDate: 2020 - 06 - 22 T14: 07: 22.193 + 00: 00
      },
      {
        questionID: 12,
        createdDate: 2020 - 06 - 20 T13: 05: 55.193 + 00: 00
      },
      {
        questionID: 13,
        createdDate: 2020 - 06 - 21 T10: 05: 23.193 + 00: 00
      }
    ]
  },
  {
    id: 2,
    questions: [{
      questionID: 11,
      createdDate: 2020 - 06 - 22 T14: 07: 22.193 + 00: 00
    }]
  }
]

如何使用汇总从mongodb获取同一查询中的问题ID和问题总数

预期资源:

[{
  'id': 1,
  totalNumberOfQuestions: 3,
  ids: [11, 12, 13]
}]

1 个答案:

答案 0 :(得分:3)

尝试这个:

db.collection.aggregate([
   {
      $project: {
         id: 1,
         totalNumberOfQuestions: { $size: "$questions" },
         ids: "$questions.questionID"
      }
   }
])