3

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.addresses. How would I do this? I am having trouble accessing the objects inside address.

I want to add this key-value pair to all addresses: "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"
        }]
    }
}
styvane
  • 59,869
  • 19
  • 150
  • 156
user1757703
  • 2,925
  • 6
  • 41
  • 62

1 Answers1

6

If I understand you want to update all you document and add "country": "USA" to every sub-document in the 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();
}
styvane
  • 59,869
  • 19
  • 150
  • 156