MongoDB: updating nested array fields in all documents in a collection

Here's my example doc:

{
    "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. How should I do it? I am having problems accessing the internal addresses of objects.

I want to add the key-value pair to all address

es: "country": "USA"

. So now this sample 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"
        }]
    }
}

      

+3


source to share


1 answer


If I understand that you want to update all documents and add "country": "USA"

to each sub-document in customer.address

. You can do this using the 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();
}

      

+5


source







All Articles