在mongodb中更新具有多个条件的数组

编程入门 行业动态 更新时间:2024-10-25 04:15:22
本文介绍了在mongodb中更新具有多个条件的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这个文件:

{ "_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中更新具有多个条件的数组

本文发布于:2023-11-22 20:52:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   数组   条件   mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!