Mongodb:在多个嵌套数组中使用条件推送元素

7jmck4yq  于 2022-12-12  发布在  Go
关注(0)|答案(2)|浏览(126)

如何将值按特定条件推送到多个嵌套数组中?
我有一份这样的文件

[
  {
    "_id": "class_a",
    "students": [
      {
        "_id": "1a",
        "name": "John",
        "grades": []
      },
      {
        "_id": "1b",
        "name": "Katie",
        "grades": []
      },
      {
        "_id": "1c",
        "name": "Andy",
        "grades": []
      },
      
    ]
  }
]

要插入到嵌套数组中的查询。(不确定此处缺少什么)

db.collection.update({
  "_id": "class_a",
  "students": {
    $elemMatch: {
      "_id": {
        "$in": [
          "1a",
          "1b"
        ]
      }
    }
  }
},
{
  $push: {
    "students.$.grades": "A+"
  }
})

得到以下结果。但我希望JohnKatiegrades中都有A+

[
  {
    "_id": "class_a",
    "students": [
      {
        "_id": "1a",
        "grades": ["A+"],
        "name": "John"
      },
      {
        "_id": "1b",
        "grades": [],
        "name": "Katie"
      },
      {
        "_id": "1c",
        "grades": [],
        "name": "Andy"
      }
    ]
  }
]

预期结果

[
  {
    "_id": "class_a",
    "students": [
      {
        "_id": "1a",
        "grades": ["A+"],
        "name": "John"
      },
      {
        "_id": "1b",
        "grades": ["A+"],
        "name": "Katie"
      },
      {
        "_id": "1c",
        "grades": [],
        "name": "Andy"
      }
    ]
  }
]

Mongo playground to test the code

nhhxz33t

nhhxz33t1#

您可以使用$[<identifier>]来只更新符合条件的项目。您的第一个{}是寻找相关的文件,而arrayFilters则是寻找文件巢状数组中的相关项目

db.collection.update(
  {_id: "class_a", students: {$elemMatch: {_id: {$in: ["1a", "1b"]}}}},
  {$push: {"students.$[item].grades": "A+"}},
  {arrayFilters: [{"item._id": {$in: ["1a", "1b"]}}], upsert: true}
)

了解它在playground example上的工作原理

d8tt03nd

d8tt03nd2#

你真的应该用arrayFilters,否则它只会匹配第一个实体。你根本不需要用$elemMatch。
Playground-https://mongoplayground.net/p/_7y89KB83Ho

db.collection.update({
  "_id": "class_a"
},
{
  $push: {
    "students.$[students].grades": "A+"
  }
},
{
  "arrayFilters": [
    {
      "students._id": {
        "$in": [
          "1a",
          "1b"
        ]
      }
    }
  ]
})

相关问题