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