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

标签 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"
}

使用以下查询,返回上述文档。

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

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

最佳答案

从 Mongo 3.6 开始,您可以 update multi-nested arrays通过组合以下运算符:

Example

以下是更新特定 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
    }
  ]
})

如果您想将查询限制为特定的 reunion ,你可以这样做:

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

更新所有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
    }
  ]
})

关于arrays - 如何更新 MongoDB 中的多级嵌套数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54055702/

相关文章:

javascript - 数组无法正确迭代并检查值 - Javascript

java.lang.NoClassDefFoundError : com/mongodb/XXXXXX Can't fix it!(使用: MongoDB Java Driver, Spigot)

mongodb - 在 mongodb 中选择 sum()

javascript - 如何将 async/await 与多个相关集合一起使用

java - 使用 Java 更新 MongoDB 中的特定字段而不是整个文档

Ruby 组合两个数组导致进程耗尽内存

C# 具有相同内存的多个数组

javascript - react 搜索和过滤方法问题

c - C 中的 strtok 和传递参数

c# - Blazor + MongoDb 身份 : Value cannot be null.(参数名称 'source')