Using $inc to update all specified fields in all documents


#1

I have some variables like this:

Im trying to increment the x/y position of each player (the position array) thats been inserted into the collection.

How would i use the $inc option to increment the x/y position in each document?

Something like : Positions.update({}, {$inc: { players[1].position[0]: 25, players[1].position[1]: 25 }});.

Whats the syntax for this? Also, if someone has a better idea how to format that data (just pairs of a name variable and x/y coordinates) to use inside a Collection for easier access, let me know.


#2

I think that it is impossible to update values inside arrays nested in arrays. You instead would want to store the position using two keys, like posX and posY. Then, to update the values, use the following code:

Positions.update({_id: /* some id */}, {$inc: {"players.1.posX": 25, "players.1.poxY": 25}});

#3

Check out this answer, I am pretty sure this is what you need:


#4

Ty.

Nice find. I ended up just changing the format of the documents to include posX and posY keys, and then updating via Positions.update({}, {$inc: {posX: 25, posY: 25}}, { multi: true });. The multi option allows fetching all documents as {} seems to only retrieve a single document. This works for now, might change it up later. :sunglasses:


#5

Please note that the multi option only works on the server. If you want it to work on the client, you would have to use a loop using perhaps the _.each function in underscore.


#6

Noted, thanks. Im simply using this to test real-time data updates before plugging in an actual data source.