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!
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 } }
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} })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With