简体   繁体   English

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

[英]MongoDB: Update nested array fields in all documents in a collection

Here is my example document: 这是我的示例文档:

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

I have several similar documents. 我有几个类似的文件。 I want to update all documents in my collection by adding another key-value pair to all customer.address es. 我想通过向所有customer.address es添加另一个键值对来更新我的集合中的所有文档。 How would I do this? 我该怎么做? I am having trouble accessing the objects inside address. 我无法访问地址内的对象。

I want to add this key-value pair to all address es: "country": "USA" . 我想将这个键值对添加到所有address es: "country": "USA" So, now that example document will look like this: 那么,现在该示例文档将如下所示:

{
    "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"
        }]
    }
}

If I understand you want to update all you document and add "country": "USA" to every sub-document in the customer.address . 如果我了解您要更新所有文档并将"country": "USA"customer.address中的每个子文档。 You can do this using the Bulk() API 您可以使用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM