根据id更新数组对象?

时间:2012-11-27 02:55:09

标签: node.js mongodb

我有一个mongo问题。我想知道是否有办法在mongo控制台命令中执行以下操作,而不是多个findupdate调用。

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

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

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

我使用了它,addToSet是有限的,如果它已经存在,它将不会将项插入数组,但它不会根据标识符更新项。在这种情况下,我真的想根据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"
}

2 个答案:

答案 0 :(得分:7)

您可以使用$位置运算符执行此操作:

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

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

答案 1 :(得分:0)

你走了:

> db.collection.insert( { array : [ { id : 1, letter : 'a' }, { id : 2, letter : 'b' } ], tester : 'tom' } );
> db.collection.findOne();
{
    "_id" : ObjectId("50b431a69a0358d590a2f5f0"),
    "array" : [
        {
            "id" : 1,
            "letter" : "a"
        },
        {
            "id" : 2,
            "letter" : "b"
        }
    ],
    "tester" : "tom"
}
> db.collection.update( { tester : 'tom' }, { $set : { 'array.1' : { id : 2, letter : 'c' } } }, false, true );
> db.collection.findOne();
{
    "_id" : ObjectId("50b431a69a0358d590a2f5f0"),
    "array" : [
        {
            "id" : 1,
            "letter" : "a"
        },
        {
            "id" : 2,
            "letter" : "c"
        }
    ],
    "tester" : "tom"
}

诀窍在于虚假,真实,虚假。 即:对于upsert为true,对于update multiple为false。

有关详细信息,请查看: http://www.mongodb.org/display/DOCS/Updating#Updating-update%28%29

相关问题