1

The title is a little bit hard to understand the first time, so here is an example. I use mongodb and have data like this :

id: String
timestamp: String
steps: [{
  action: 1,
  timestamp: String
}, {
  action: 2,
  timestamp: String
}, ...
]

I would like to add a new field to each step, let's say bot: false. I tried an update like :

{ $set: { 'steps': { 'bot': false } } }

However this replaced the whole step, losing action/timestamp. I also tried :

{ $set: { 'steps.bot': false } }

This didn't work either, because steps is an array.

I also looked at the $each modifier, however it doesn't seem to work with $set.

Any idea ? Thanks

Antek
  • 1,167
  • 3
  • 10
  • 18

1 Answers1

4

As per your question I think your documents structure like below

    {
    "_id" : ObjectId("54996f980e64b1a2fcb4824e"),
    "id" : "1",
    "timestamp" : "Tue, 23 Dec 2014 13:37:33 GMT",
    "steps" : [
        {
            "action" : 1,
            "timestamp" : "Tue, 23 Dec 2014 13:37:40 GMT"

        },
        {
            "action" : 2,
            "timestamp" : "Tue, 23 Dec 2014 13:37:40GMT"

        }
    ]
}

And in above document you want to add new field like steps.bot:false so you should use following javascript to update nested documents

    db.collectionName.find({
   "steps":{"$exists":true}}).forEach(function(data){
    for(var i=0;i<data.steps.length;i++) {
      db.demo.update(
     { 
         "_id": data._id, 
         "steps.action": data.steps[i].action 
     },
     {
         "$set": {
           "steps.$.bob":
               false
         }
     },true,true
      );
  }
})
Neo-coder
  • 7,715
  • 4
  • 33
  • 52