1

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.

2 Answers 2

2

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 });
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use $push operator to update array in a document.

Try This:

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

7 Comments

this will add the itemSpec as "an element" of the items array. OP wants to add it inside the actual elements instead
It creating new array element as below, I have to update as I mentioned above { "items": [ { "itemList": { "rejected": true }, "fProcBy": "automatic" }, { "itemList": { "rejected": true }, "fProcBy": "automatic" }, { "itemSpec": { "approved": true } } ] }
I did not get what you wanted to say!!! can you tell me what is the issue
did you try "items.0"?
code u provided is adding new array item[2], in the given example, the code has to insert the itemSpec, in available array elements as mentioned in the after process
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.