Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb Increment value inside nested array

I´m using mongotemplate for Spring, and I was wondering how I could increment a value of one of my documents that I have in an array atomically. Imagine that we have

{'a':1,
   b:[{_id:341432,
       c:2
      },
      {_id:341445,
       c:3
      }]};

What I would like is increment c from 3 to 4 for the _id 341445

I have been using findAndModify but I dont know how can I make it for a nested document in an array.

Regards.

like image 585
paul Avatar asked Apr 16 '13 13:04

paul


1 Answers

To update an element in an array field, you can use the positional $ operator

For example, the following js increments c from 3 to 4 for _id 341445:

db.collection.update({a:1, "b._id":341445} , {$inc:{"b.$.c":1}})
like image 177
Linda Qin Avatar answered Oct 05 '22 00:10

Linda Qin