1

I am trying to update an array inside document in which i want to perform update operation based on a greater than condition.

Here is my document:

{  
  _id:some_id,
  name:"test",
  data:[
         { __id:1,
           __data:[{a:"something"}]
          },
           { __id:2,
           __data:[{a:"something"}]
          },
           { __id:3,
           __data:[{a:"something"}]
          }....
        ]
}

I want to subtract 1 from __id of every element in the data array if its __id is greater than 2

Currently i am doing this but it is not working

db.collection('collection_name').update({name:"test","data.__id":{$gt:2}},{$inc:{"data.__id":-1}},{multi:true})
Faiz Khan
  • 288
  • 1
  • 9

1 Answers1

1

You have to use $ positional operator to update value inside an array

db.getCollection('test').update(
 { "name": "test" , "data.__id": { "$gt": 2 }},
 { "$inc": { "data.$.__id": -1 }},
 { "multi": true }
)
Ashh
  • 44,693
  • 14
  • 105
  • 132