查找,更新并返回文档内的数组对象(mongodb)

时间:2018-07-02 07:16:51

标签: javascript mongodb mongoose

我有一堆文件,格式如下:

{
    _id: "5b38c85f213751038ff4d0bb",
    classes: [
      {
        _id: "5b38c85f21375103ytg65ju7",
        standard: "12",
        numberOfStudents: 45
      },
      {
        _id: "5b38c85f2137510370987hgd",
        standard: "11",
        numberOfStudents: 51
      },
    ]
}

我要

  1. _id和特定类别的_id搜索文档集合。
  2. 更新该课程的numberOfStudents
  3. 仅返回类对象。

因此对于_id: "5b38c85f213751038ff4d0bb"classes._id: "5b38c85f21375103ytg65ju7",更新numberOfStudents: 43我期望的结果是:

{
  _id: "5b38c85f21375103ytg65ju7",
  standard: "12",
  numberOfStudents: 43
}

我尝试了几件事,但是它们都返回了整个文档,但没有返回我想要的样子。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

data

输出

db.collection.aggregate([
  { "$match": { "_id": "5b38c85f213751038ff4d0bb" }},
  { "$addFields": {
    "classes": {
      "$filter": {
        "input": "$classes",
        "as": "class",
        "cond": {
          "$eq": [
            "$$class._id",
            "5b38c85f21375103ytg65ju7"
          ]
        }
      }
    }
  }},
  { "$unwind": "$classes" },
  { "$replaceRoot": { "newRoot": "$classes" }},
  { "$project": {
    "_id": 1,
    "numberOfStudents": { "$literal": 43 },
    "standard": 1
  }}
])

尝试here