如何在MongoDB中更新多层嵌套数组? [英] How can I update a multi level nested array in MongoDB?
问题描述
如何更新具有多层数组嵌套级别的文档中的记录?
How can I update a record in a document with multiple levels of array nesting?
我的文档结构如下:
{
"_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"
}
使用以下查询,向我返回上述文档.
Using the following query, returns me the document mentioned above.
db.proyectos.find({
_id:ObjectId("5bfa09f0a0441f38d45dcc9c"),
"reuniones._id":ObjectId("5bfa09f0a0441f38d45dcc99"),
"reuniones.participantes.nomina":2
})
我想用名词2更新参与者的公司领域.
I want to update the firma field of participant with nomina 2.
推荐答案
Since Mongo 3.6, you can update multi-nested arrays by combining the following operators:
$set
(to update a specific field)$[]
(to match any item in an array)$[<identifier>]
(to match specific items in an array)
在这里,您可以更新具有reuniones
数组的特定proyectos
文档,该文档具有participantes
数组,该数组的对象的字段nomina
等于2
:
Here's how you can update a specific proyectos
document that has a reuniones
array that has a participantes
array that has an object with the field nomina
equal to 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
,则可以执行以下操作:
If you wanted to limit your query to a specific reunion
, you can do:
db.proyectos.update({
_id: ObjectId("5bfa09f0a0441f38d45dcc9c"),
}, {
$set: {
"reuniones.$[i].participantes.$[j].firma": <your update>
},
}, {
arrayFilters: [
{
"i._id": ObjectId("5bfa09f0a0441f38d45dcc99")
},
{
"j.nomina": 2
}
]
})
要更新所有满足上述条件的proyectos
,只需省略_id
查询:
To update all proyectos
satisfying the above condition, just omit the _id
query:
// 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
}
]
})
这篇关于如何在MongoDB中更新多层嵌套数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!