0

I have a document like that :

{
     _id: ".....",
     messages: [
        {
          ....
          votes: 2
        },
        {
          ....
          votes: 2
        }
     ]
}

I would like to increment ALL votes field in the array in the same request.

How to do that ? The $ operator select only the first element.

Thank you !

jeremieca
  • 1,156
  • 2
  • 13
  • 38

1 Answers1

0

You might have to do this with some JS loops:

db.collection.find( { "_id": SOME_ID } ).forEach( function( doc ) {
  for ( i in doc.messages ){
    doc.messages[ i ].votes += 1;
  }
  db.collection.save( doc );  
} );

What I'm doing here is iterating over each document in the cursor and iterating over it's messages property incrementing each element's votes attribute by one.

Lix
  • 47,311
  • 12
  • 103
  • 131
  • The problem is with the following situation : A user1 want to increment. But during the increment is progressing a user2 also want to increment the same values. So, user1 and user2 find the same initial document and save the votes increment by 1. User1 save, then user2 save and erase the user1 increment. Do you understand the problem ? – jeremieca Jul 17 '14 at 14:25
  • @jeremieca - yes. But these simultaneous requests and updates to the same documents are handled at the mongo level. You don't need to concern yourself with parallel requests to the same resource. – Lix Jul 17 '14 at 14:47
  • If there is a conflict, mongodb choose de highest version. So it's a problem. It's why I would like to use $inc. – jeremieca Jul 17 '14 at 14:58
  • I don't understand what you mean by the "highest version". Mongo will handle requests in the order that they arrive to the server. – Lix Jul 17 '14 at 14:59