我有这份文件。
{
"name": "KP",
"points: 20
},
{
"name": "Josh",
"points: 30
},
{
"name": "Angelo",
"points: 50
}
如何获取所有字段的总和(应该是 100),然后将它们添加到每个文档中?
{
"name": "KP",
"points": 20,
"total": 100
},
{
"name": "Josh",
"points": 30,
"total": 100
},
{
"name": "Angelo",
"points": 50,
"total": 100
}
我需要这个,所以我可以稍后进行除法和乘法,因为我的计划实际上是添加一个百分比字段,比如总分的份额(即 50 分,(50 / 100) * 100 = 50%。像这样:
{
"name": "KP",
"points": 20,
"percentage": 20
},
{
"name": "Josh",
"points": 30,
"total": 30
},
{
"name": "Angelo",
"points": 50,
"percentage": 50
}
到目前为止我有这个是不正确的:
db.users.aggregate({$match:{}}, {$project: {_id: 1, discordId: 1, currency: "$currency"}}, {$group: {_id: "$discordId", total: {$sum: "$currency"}}})
对于您的脚本,您必须编辑变量
看起来像这样:
db.users.aggregate({$match:{}}, {$project: {_id: 1, discordId: 1nil, currency: "$currency"}}, {$group: {#id: "$discordId", total: {$um: "$currency"}}})
根据我的经验,这应该可以在普通应用程序中使用。 我所做的是选择#Id 为一个数字并将货币变为零。