Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a value in a nested object?

Tags:

mongodb

I am messing around with mongodb and node.js this weekend and I'm having some trouble getting through the mongodb docs regarding updating nested objects/documents.

I have a collection in which the documents look like this..

{
 gameName: "string",
 slug: "string",
 players: [{playerName, playerScore}, ...]
}

I'm trying to find out how to increment the value of playerScore based on the playerName.

I suppose this mostly comes down to me not understanding NoSQL method. I even have second thoughts about using an array for the players, so any input would be appreciated.

Thanks!

like image 931
JackM Avatar asked May 06 '12 14:05

JackM


2 Answers

The structure you want is:

{
 gameName: "string",
 slug: "string",
 players: [ { playerName: "string", playerScore: number} ] , ...]
}

To increment player score by one if his name is Joe you would use:

db.collection.update( {"players.playerName":"Joe"}, { $inc : { "players.$.playerScore" : 1 } }
like image 108
Asya Kamsky Avatar answered Nov 11 '22 16:11

Asya Kamsky


I believe that you would have to structure your document instead like

{
 gameName: "string",
 slug: "string",
 players: {playerName: {score: playerScore}},
}

Then you can update the score with:

db.games.update({"gameName": "string"},
                {$inc: {"players.playerName.score": 1}
                })
like image 6
Chris AtLee Avatar answered Nov 11 '22 17:11

Chris AtLee