MongoDB更新:-更新嵌套在数组中的多个对象(在多个文档中)

MongoDB更新:-更新嵌套在数组中的多个对象(在多个文档中),mongodb,mongoose,Mongodb,Mongoose,我的收藏如下: { "_id" : "", "team" : "avenger", "persons" : [ { "name" : "ABC", "class" : "10", "is_new" : true }, { "name" : "JHK", "class" : "12", "is_new" : true }, { "name" : "BNH",

我的收藏如下:

{
  "_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
    }
  ]
}
我的目标是在“persons”中查找所有包含嵌套对象的文档,其中“class”是“10”,并将“is_new”字段更新为“false”

我正在使用mongoose更新,将“multi”设置为true

查询:

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

{
  multi : true
}
更新:

我试过的第一个方法是:

{
  $set : {
    "persons.$.is_new" : false
  }
}
第二个是:

{
  $set : {
    "persons.$[].is_new" : false
  }
}
问题是:在更新操作中使用$只更新“persons”数组中所有匹配文档的第一个匹配项

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

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

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


是否不能使用单个查询完成此操作在文档中循环是我唯一的选择吗?

您需要设置过滤后的位置运算符标识符

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