【问题标题】:Mongodb: Push element in multiple nested array with conditionMongodb:使用条件将元素推送到多个嵌套数组中
【发布时间】:2022-12-06 20:23:29
【问题描述】:

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

[
  {
    "_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

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    您可以使用 $[<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 上的工作原理

    【讨论】:

      【解决方案2】:

      你真的应该为这些使用arrayFilters,否则它只会匹配第一个实体。您根本不需要使用 $elemMatch。

      游乐场 - https://mongoplayground.net/p/_7y89KB83Ho

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

      【讨论】:

      • 需要使用$elemMatch才能找到相关文件。您的回答将在所有项目上尝试arrayFilters全部文件
      猜你喜欢
      • 1970-01-01
      • 2020-07-08
      • 2020-12-30
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-21
      相关资源
      最近更新 更多