本周末我正在搞乱mongodb和node.js,我在通过关于更新嵌套对象/文档的mongodb文档时遇到了一些麻烦.
我有一个文件看起来像这样的集合..
{
gameName: "string",
slug: "string",
players: [{playerName, playerScore}, ...]
}
Run Code Online (Sandbox Code Playgroud)
我试图找出如何根据playerName增加playerScore的值.
我想这主要归结于我不理解NoSQL方法.我甚至对于为玩家使用阵列有了第二个想法,所以任何输入都会受到赞赏.
谢谢!
Asy*_*sky 19
你想要的结构是:
{
gameName: "string",
slug: "string",
players: [ { playerName: "string", playerScore: number} ] , ...]
}
Run Code Online (Sandbox Code Playgroud)
如果他的名字是乔,将玩家得分增加1,你会使用:
db.collection.update( {"players.playerName":"Joe"}, { $inc : { "players.$.playerScore" : 1 } }
Run Code Online (Sandbox Code Playgroud)
我相信你必须构建你的文档而不是像
{
gameName: "string",
slug: "string",
players: {playerName: {score: playerScore}},
}
然后你可以用以下内容更新分数:
db.games.update({"gameName": "string"},
{$inc: {"players.playerName.score": 1}
})