我有这份文件:
{
"_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)中。
如果我将字段“ name” 更改为“ a” 并运行相同的更新,那么我得到正确的结果:
{
"_id" : ObjectId("5b673f525ef92ec6ef16504e"),
"events" : [
{
"a" : "Winner",
"map" : 0,
"something" : []
},
{
"a" : "Winner",
"map" : 2,
"something" : [
{
"something" : "test"
}
]
},
{
"a" : "DifferentName",
"map" : 2,
"something" : []
}
]
}
现在您可以看到“某物”:“测试” 在正确的位置(第二个事件)。这是因为我用过“ name” 和“ name” 是Mongo中的某种保留关键字吗?
答案 0 :(得分:1)
如果数组中有多个条件要匹配,则.Dot
表示法不适用于更新查询。
您需要使用$elemMatch
来匹配数组中的两个字段
db.getCollection('test').updateOne(
{
"_id": ObjectId("5b673f525ef92ec6ef16504e"),
"events": { "$elemMatch": { "name": "Winner", "map": 2 }}
},
{
"$push": { "events.$.something": { "something": "test" }}
}
)