在mongodb中使用多个条件更新数组 [英] Update array with multiple conditions in mongodb

查看:79
本文介绍了在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" : []
        }
    ]
}

现在您可以看到某物":测试" 在正确的位置(第二个事件).这是因为我使用了"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中使用多个条件更新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆