Mongodb按id更新嵌套数组
我有以下文档,希望更新Mongodb按id更新嵌套数组,mongodb,Mongodb,我有以下文档,希望更新状态 文档ID:ObjectId(“5a4e5a448b70d50e34d204a5”) 目标ID:ObjectId(“5a4e5a438b70d50e34d203ea”) 我不知道如何将状态更新为例如4 { "_id" : ObjectId("5a4e5a448b70d50e34d204a5"), "name" : "Wirtschaftsdienst", "date" : ISODate("2012-10-07T00:00:00.000Z"), "c
状态
文档ID:ObjectId(“5a4e5a448b70d50e34d204a5”)
目标ID:ObjectId(“5a4e5a438b70d50e34d203ea”)
我不知道如何将状态更新为例如4
{
"_id" : ObjectId("5a4e5a448b70d50e34d204a5"),
"name" : "Wirtschaftsdienst",
"date" : ISODate("2012-10-07T00:00:00.000Z"),
"comment" : null,
"tasks" : [
{
"name" : "Speisen und Getränke",
"sections" : [
{
"start" : 46800,
"end" : 72000,
"entirely" : true,
"assistants" : [
{
"assistant" : {
"_id" : ObjectId("5a4e5a438b70d50e34d203ea")
},
"state" : 3
},
{
"assistant" : {
"_id" : ObjectId("5a4e5a438b70d50e34d203f4")
},
"state" : 3
}
]
}
]
}
]
}
使用位置运算符和完成您的工作
请尝试以下查询:
db.collection.update(
{"_id" : ObjectId("5a4e5a448b70d50e34d204a5")},
{$set: {"tasks.$[].sections.$[].assistants.$[element].state":4}},
{arrayFilters: [ {"element.assistant":{"_id" :
ObjectId("5a4e5a438b70d50e34d203ea")} }
], multi:true}
)
输出为:
/* 1 */
{
"_id" : ObjectId("5a4e5a448b70d50e34d204a5"),
"name" : "Wirtschaftsdienst",
"date" : ISODate("2012-10-07T00:00:00.000Z"),
"comment" : null,
"tasks" : [
{
"name" : "Speisen und Getränke",
"sections" : [
{
"start" : 46800,
"end" : 72000,
"entirely" : true,
"assistants" : [
{
"assistant" : {
"_id" : ObjectId("5a4e5a438b70d50e34d203ea")
},
"state" : 4.0
},
{
"assistant" : {
"_id" : ObjectId("5a4e5a438b70d50e34d203f4")
},
"state" : 3.0
}
]
}
]
}
]
}
非常感谢。这看起来很有希望,但我得到了一个错误:不能使用部分(tasks of tasks.$[].sections.$[].assistants.$[element].state)遍历元素({tasks:[{name:[{name:'Speisen und Getränke],sections:[{start:46800,end:72000,all:true,assistants:[{assistant:{id:ObjectId('5a4e5a5e5e5e5a4e5a438b70d50e34d203ea')),状态:3},{assistant:{u id:ObjectId('5a4e5a438b70d50e34d203f4')},状态:3}]}})你是在执行来自robomongo的查询吗?你需要从MongoShell执行它,最好是Mongo3.6。即使我在第三方工具(如robo)中尝试时也遇到了错误,一旦我在MongoShell中尝试了相同的查询,它就成功了。非常感谢!我已经有了mongodb 3.6,但我的nodejs mongoclient是3.x之前的版本,不支持
ar光线过滤器
。现在一切正常;-)