MongoDB:更新集合中所有文档中的嵌套数组字段

时间:2015-07-30 19:59:05

标签: javascript mongodb mongodb-query

这是我的示例文档:

{
    "isUpdated": false,
    "isDeleted": false,
    "customer": {
        "name": "John Doe",
        "address": [{
            "houseNum": 5,
            "streetName": "Example Avenue",
            "postalCode": "90210"
        }, {
            "houseNum": 15,
            "streetName": "Second Example Avenue",
            "postalCode": "91210"
        }]
    }
}

我有几个类似的文件。我想通过向所有customer.address es添加另一个键值对来更新我的集合中的所有文档。我该怎么做?我无法访问地址内的对象。

我想将此键值对添加到所有address es:"country": "USA"。所以,现在该示例文档将如下所示:

{
    "isUpdated": false,
    "isDeleted": false,
    "customer": {
        "name": "John Doe",
        "address": [{
            "houseNum": 5,
            "streetName": "Example Avenue",
            "postalCode": "90210",
            "country": "USA"
        }, {
            "houseNum": 15,
            "streetName": "Second Example Avenue",
            "postalCode": "91210",
            "country": "USA"
        }]
    }
}

1 个答案:

答案 0 :(得分:5)

如果我了解您要更新所有文档并将"country": "USA"添加到customer.address中的每个子文档。您可以使用Bulk() API

执行此操作
var bulk = db.collection.initializeOrderedBulkOp();
var count = 0;

db.collection.find().forEach(function(doc){
    var addr = doc["customer"]["address"]; 
    for (var i = 0; i < addr.length; i++) {
        bulk.find({ 
            "_id": doc._id, 
            "customer.address": { "$elemMatch": {
                "houseNum": addr[i][ "houseNum" ], 
                "streetName": addr[i][ "streetName" ]}}
        }).update({
            "$set": { "customer.address.$.country": "USA" }
        })} 
    count++;
    if ( count % 1000 == 0 ) {
        // Execute per 1000 operations and re-init.
        bulk.execute();
        bulk = db.collection.initializeOrderedBulkOp();
    }
})

// Clean up queues
if ( count % 1000 != 0 ){
    bulk.execute();
}