如何更新 MongoDB 中的多级嵌套数组?

Gib*_*rán 5 arrays mongodb

如何更新具有多级数组嵌套的文档中的记录?

我的文档结构如下:

{
  "_id": "5bfa09f0a0441f38d45dcc9c",
  "nombre": "PROYECTO MAIN",
  "area": "Sistemas",
  "fecha": "27/01/2018",
  "reuniones": [
    {
      "_id": "5bfa09f0a0441f38d45dcc99",
      "objetivo": "Objetivo MODIFICADO",
      "fecha": "25/10/2018",
      "participantes": [
        {
          "nomina": 1,
          "nombre": "MODIFICADO",
          "rol": "rol",
          "area": "area",
          "firma": "url/imagen.jpg"
        },
        {
          "nomina": 2,
          "nombre": "nombre 2",
          "rol": "rol",
          "area": "area",
          "firma": "url/imagen.jpg"
        }
      ]
    }
  ],
  "_class": "proyecto"
}
Run Code Online (Sandbox Code Playgroud)

使用以下查询,返回上面提到的文档。

 db.proyectos.find({
    _id:ObjectId("5bfa09f0a0441f38d45dcc9c"),
    "reuniones._id":ObjectId("5bfa09f0a0441f38d45dcc99"), 
    "reuniones.participantes.nomina":2 
 })
Run Code Online (Sandbox Code Playgroud)

我想用nomina 2更新参与者的firma字段。

nem*_*035 10

从 Mongo 3.6 开始,您可以通过组合以下运算符来更新多嵌套数组

  • $set (更新特定字段)
  • $[] (匹配数组中的任何项目)
  • $[<identifier>] (匹配数组中的特定项目)

例子

以下是更新proyectos具有reuniones数组的特定文档的方法,该 数组的participantes数组具有字段nomina等于的对象2

// update a specific proyectos document
// that has a field "reuniones" which is an array
// in which each item is an object with a field "participantes" that is an array
// in which each item is an object that has a field "nomina" equal to 2
db.proyectos.update({
  _id: ObjectId("5bfa09f0a0441f38d45dcc9c"),
}, {
  $set: {
    "reuniones.$[].participantes.$[j].firma": <your update>
  },
}, { 
  arrayFilters: [
    {
      "j.nomina": 2
    }
  ]
})
Run Code Online (Sandbox Code Playgroud)

如果您想将查询限制为特定的reunion,您可以执行以下操作:

db.proyectos.update({
  _id: ObjectId("5bfa09f0a0441f38d45dcc9c"),
}, {
  $set: {
    "reuniones.$[i].participantes.$[j].firma": <your update>
  },
}, { 
  arrayFilters: [
    {
      "i._id": ObjectId("5bfa09f0a0441f38d45dcc99")
    },
    {
      "j.nomina": 2
    }
  ]
})
Run Code Online (Sandbox Code Playgroud)

要更新所有proyectos满足上述条件的,只需省略_id查询:

// update all proyectos
// that have a field "reuniones" which is an array
// in which each item is an object with a field "participantes" that is an array
// in which each item is an object that has a field "nomina" equal to 2    
db.proyectos.update({}, {
  $set: {
    "reuniones.$[].participantes.$[j].firma": <your update>
  },
}, { 
  arrayFilters: [
    {
       "j.nomina": 2
    }
  ]
})
Run Code Online (Sandbox Code Playgroud)