首页 > 解决方案 > MongoDB更新:-更新嵌套在数组中的多个对象(在多个文档中)

问题描述

我的收藏如下:

{
  "_id" : "",
  "team" : "avenger",
  "persons" : [
    {
      "name" : "ABC",
      "class" : "10",
      "is_new" :  true
    },
    {
      "name" : "JHK",
      "class" : "12",
      "is_new" :  true
    },
    {
      "name" : "BNH",
      "class" : "10",
      "is_new" :  true
    }
  ]
},
{
  "_id" : "",
  "team" : "adrenaline",
  "persons" : [
    {
      "name" : "HTU",
      "class" : "11",
      "is_new" :  true
    },
    {
      "name" : "NVG",
      "class" : "10",
      "is_new" :  true
    },
    {
      "name" : "SED",
      "class" : "8",
      "is_new" :  true
    }
  ]
}

我的目标是在“类”为“10”的“persons”中查找包含此类嵌套对象的所有此类文档,并将“is_new”字段更新为“false”

我正在使用“multi”设置为 true 的猫鼬更新

询问 :

{                
  persons: { $elemMatch: { class: "10" } }
}

选项:

{
  multi : true
}

更新 :

我尝试过的第一个是:

{
  $set : {
    "persons.$.is_new" : false
  }
}

第二个是:

{
  $set : {
    "persons.$[].is_new" : false
  }
}

问题是:在更新操作中使用 $ 仅更新“persons”数组中所有匹配文档的第一个匹配项。

如果我使用$[],它会更新匹配文档中“persons”数组的所有对象

解决方法可以是使用循环进行更新操作,但我认为这不应该是理想的情况。

我在文档中看不到任何内容,但发现有人报告此更新操作问题。

这不能使用单个查询来完成吗?循环浏览文档是我唯一的选择吗?

标签: mongodbmongoose

解决方案


您需要设置过滤的位置运算符$[<identifier>]标识符

Model.update(
  { "persons": { "$elemMatch": { "class": "10" }}},
  { "$set" : { "persons.$[e].is_new" : false }},
  { "arrayFilters": [{ "e.class": "10" }], "multi" : true }
)

推荐阅读