在 Mongo 数据库中添加和更新子数组值

Add and update child arrays value in Mongo db

我想在 mongo 数据库集合“Scdtls”中的以下 json 结构的数组中添加值。 我只需要在 "Type": "Fees""IsCurrentVersion": true.

的地方添加值
  {
    "_id": ObjectId("60e71243b484cf3ec22a6845"),
    "Item": "School",
    "Text": "School Details",
    "Types": [
      {
        "Type": "Library",
        "Values": [
          {
            "IsCurrentVersion": false,
            "KeyWords": [
              {
                "_id": ObjectId("611a4f113800d6af3fc4814f"),
                "Value": "Physics"
              }
            ]
          }
        ]
      },
      {
        "Type": "Fees",
        "Values": [
          {
            "IsCurrentVersion": false,
            "KeyWords": [
              {
                "_id": ObjectId("611a4f113800d6af3fc4814f"),
                "Value": "Admission"
              },
              {
                "_id": ObjectId("611a4f113800d6af3fc4814k"),
                "Value": "Canteen"
              }
            ]
          },
          {
            "IsCurrentVersion": true,
            "KeyWords": [
              {
                "_id": ObjectId("611a4f113800d6af3fc4814g"),
                "Value": "Tution"
              }
            ]
          }
        ]
      }
    ]
  }

这就是我正在尝试的方式

db.Scdtls.update({
  "Item": "School",
  "Types.Type": "Fees",
  "Types.Values.IsCurrentVersion": true
},
{
  "$push": {
    "Types.1.Values.$[].KeyWords": {
      "_id": ObjectId(),
      "Value": "Sports"
    }
  }
})

但它也在 "IsCurrentVersion": false 中的 "Type" : "Fees" 中添加了 "Value": "Sports"。 无法理解原因。

如果我理解正确,您可以使用 "arrayFilters" 进行您想要的更新,如下所示:

db.Scdtls.update({
  "Item": "School",
  "Types.Type": "Fees",
  "Types.Values.IsCurrentVersion": true
},
{
  "$push": {
    "Types.$[x].Values.$[y].KeyWords": {
      "_id": ObjectId("deadbeafcafebabec0deface"),
      "Value": "Sports"
    }
  }
},
{
  "arrayFilters": [
    { "x.Type": "Fees" },
    { "y.IsCurrentVersion": true }
  ]
})

mongoplayground.net 上试用。