【发布时间】:2015-02-19 17:45:05
【问题描述】:
我想更新一个嵌套在数组值中的数组值:即设置
status = enabled
在哪里alerts.id = 2
{
"_id" : ObjectId("5496a8ed49847b6cd7c7b350"),
"name" : "joe",
"locations" : [
{
"name": "my location",
"alerts" : [
{
"id" : 1,
"status" : null
},
{
"id" : 2,
"status" : null
}
]
}
]
}
我会使用位置 $ 字符,但不能在语句中使用它两次 - 还不支持多位置运算符:https://jira.mongodb.org/browse/SERVER-831
如何发布一条语句以仅更新匹配 id 为 2 的警报的状态字段?
更新
如果我按如下方式更改架构:
{
"_id" : ObjectId("5496ab2149847b6cd7c7b352"),
"name" : "joe",
"locations" : {
"my location" : {
"alerts" : [
{
"id" : 1,
"status" : "enabled"
},
{
"id" : 2,
"status" : "enabled"
}
]
},
"my other location" : {
"alerts" : [
{
"id" : 3,
"status" : null
},
{
"id" : 4,
"status" : null
}
]
}
}
}
然后我可以使用:
update({"locations.my location.alerts.id":1},{$set: {"locations.my location.alerts.$.status": "enabled"}});
问题是我无法在警报 ID 上创建索引 :-(
【问题讨论】:
-
如果可能,您可能需要重新考虑您的数据模型。像这样的嵌套数组在 MongoDB 中操作起来很棘手。
-
感谢Tommi的回复,看来是多位操作员jira.mongodb.org/browse/SERVER-831