根据ID更新数组对象? [英] Update array object based on id?

查看:52
本文介绍了根据ID更新数组对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个mongo问题.我想知道是否有一种方法可以在mongo控制台命令中执行以下操作,而不是多个findupdate调用.

I'm having a bit of a mongo issue. I was wondering if there was a way to do the following in a mongo console command rather then multiple find and update calls.

{
    "_id" : ObjectId("50b429ba0e27b508d854483e"),
    "array" : [
        {
            "id" : "1",
            "letter" : "a"
        },
        {
            "id" : "2",
            "letter" : "b"
        }
    ],
    "tester" : "tom"
}

我想用这个新的数组项更新对象

I want to update the object with this new array item

{
    "id": "2",
    "letter": "c"
}

我使用了它,addToSet是受限制的,如果它已经存在,它不会在数组中插入项目,但不会基于标识符更新项目.在这种情况下,我真的很想根据id更新此条目.

I used this, addToSet is limited, it won't insert an item into the array if it is already there but it will not update an item based on an identifier. In this case I would really like to update this entry based on the id.

db.soup.update({
     "tester": "tom"
 }, {
     $addToSet: {
         "array": {
             "id": "2",
             "letter": "c"
         }
     }
});

这给了我

{
    "_id" : ObjectId("50b429ba0e27b508d854483e"),
    "array" : [
        {
            "id" : "1",
            "letter" : "a"
        },
        {
            "id" : "2",
            "letter" : "b"
        },
        {
            "id" : "2",
            "letter" : "c"
        }
    ],
    "tester" : "tom"
}

当我真正想要的是:

{
    "_id" : ObjectId("50b429ba0e27b508d854483e"),
    "array" : [
        {
            "id" : "1",
            "letter" : "a"
        },
        {
            "id" : "2",
            "letter" : "c"
        }
    ],
    "tester" : "tom"
}

推荐答案

您可以使用 $ 位置运算符可做到这一点:

You can use the $ positional operator to do this:

db.soup.update(
    {_id: ObjectId("50b429ba0e27b508d854483e"), 'array.id': '2'}, 
    {$set: {'array.$.letter': 'c'}})

更新对象中的$用作array的第一个元素的占位符,以匹配查询选择器.

The $ in the update object acts as a placeholder for the first element of array to match the query selector.

这篇关于根据ID更新数组对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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