Sabareesh Gunasekaran
Sabareesh Gunasekaran

Reputation: 41

Insert object into MongoDB array element

I have to insert an object in every array in the MongoDB document. The items array displayed below has itemList; in every itemList I have to insert a itemSpec. The desired document shape before and after the process is shown below:

Before process

{
  "items": [
    {
      "itemList":{
        "rejected": true
      },
      "fProcBy": "automatic"
    },
    {
      "itemList":{
        "rejected": true
      },
      "fProcBy": "automatic"
    }
  ]
}

After process:

{
  "items": [
    {
      "itemList":{
        "rejected": true
      },
      "itemSpec":{
        "approved": true
      },
      "fProcBy": "automatic"
    },
    {
      "itemList":{
        "rejected": true
      },
      "itemSpec":{
        "approved": true
      },
      "fProcBy": "automatic"
    }
  ]
}

So in each element of the items array there has to be inserted a new object property itemSpec.

Upvotes: 1

Views: 695

Answers (2)

Shantanu Madane
Shantanu Madane

Reputation: 615

Use $push operator to update array in a document.

Try This:

db.test.update({"_id":"yourUniqueId"}, 
              {$push: {  "items":{ "itemSpec":{"approved": true}}}});

Upvotes: 1

DAXaholic
DAXaholic

Reputation: 35398

I am not aware of a solution which does it in a single run, but with the following simple script the maximal number of iterations is equal to the maximal number of array elements you have in a single documents, which is probably not so high (but it's just a guess as I have no further information about your data):

var q = { "items.itemSpec": null };
var u = { 
    $set: {
        "items.$.itemSpec" : {
            "approved": true
        }
    }
};
var yourColl = db.getCollection('fooBar');
while (yourColl.find(q).count() > 0) {
    yourColl.update(q, u, { multi: true });
}

Upvotes: 2

Related Questions