问题描述
我有这个文件:
{
"_id" : ObjectId("5b673f525ef92ec6ef16504e"),
"events" : [
{
"name" : "Winner",
"map" : 0,
"something" : []
},
{
"name" : "Winner",
"map" : 2,
"something" : []
},
{
"name" : "DifferentName",
"map" : 2,
"something" : []
}
]
}
如果我运行以下更新:
db.getCollection('test').updateOne({
"_id": ObjectId("5b673f525ef92ec6ef16504e"),
"events.name": "Winner",
"events.map": 2
},
{$push: {
"events.$.something": {
something: "test",
}
}
})
我得到了糟糕的结果:
{
"_id" : ObjectId("5b673f525ef92ec6ef16504e"),
"events" : [
{
"name" : "Winner",
"map" : 0,
"something" : [
{
"something" : "test"
}
]
},
{
"name" : "Winner",
"map" : 2,
"something" : []
},
{
"name" : "DifferentName",
"map" : 2,
"something" : []
}
]
}
这是错误的,因为 "something" : "test" 应该在第二个元素中,其中映射等于 2.
This is wrong, because "something" : "test" should be in the second element, where the map is equal to 2.
如果我将字段 "name" 更改为 "a" 并运行相同的更新,那么我会得到正确的结果:
If I change the field "name" to "a" and run the same update, then I get the right result:
{
"_id" : ObjectId("5b673f525ef92ec6ef16504e"),
"events" : [
{
"a" : "Winner",
"map" : 0,
"something" : []
},
{
"a" : "Winner",
"map" : 2,
"something" : [
{
"something" : "test"
}
]
},
{
"a" : "DifferentName",
"map" : 2,
"something" : []
}
]
}
现在您可以看到,"something" : "test" 位于正确的位置(第二个事件).这是因为我使用了 "name" 并且 "name" 是 Mongo 中的某种保留关键字吗?
Now you can see, that "something" : "test" is in the right place (second event). Is this because I have used "name" and "name" is some kind of reserved keyword in Mongo?
推荐答案
当数组中有多个条件要匹配时,.Dot
表示法不适用于更新查询.
When there are multiple conditions to match inside an array then the .Dot
notation doesn't work with update query.
您需要使用$elemMatch
匹配数组中的两个字段
You need to use
$elemMatch
to match exact two fields inside an array
db.getCollection('test').updateOne(
{
"_id": ObjectId("5b673f525ef92ec6ef16504e"),
"events": { "$elemMatch": { "name": "Winner", "map": 2 }}
},
{
"$push": { "events.$.something": { "something": "test" }}
}
)
这篇关于在mongodb中更新具有多个条件的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!