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})
0

1 Answer 1

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

5 Comments

above query only update single document not all documents matching the condition
Updated my answer
i tried that before but it wasn't working, and i am also using a callback with this so is that a problem
No callback or .then is necessary here. multi:true didn't work?
yes take a look at this : collection.update({"name":data.toRoom,"tab_data.__id":{"$gt":parseInt(data.removeWithId)}},{"$inc":{"tab_data.$.__id":-1}},{"multi": true},callback)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.