gpt4 book ai didi

arrays - mongodb,对象数组上的$sum

转载 作者:可可西里 更新时间:2023-11-01 10:00:04 27 4
gpt4 key购买 nike

<分区>

我是 mongodb 的新手,可能是我遗漏了什么。但是在 Internet 上有很多样本,仍然无法在属于对象数组的一个字段上获得总数。这是我正在做的:

db.collection.insertMany([
{
id: "6002010011500",
balance: [
{ type: "PR", amount: "1000" },
{ type: "IN", amount: "300" }
]
},
{
id: "5001010001005",
balance: [
{ type: "PR", amount: "-3000" },
{ type: "IN", amount: "-600" }
]
}
])

尝试以不同方式获取总量:

db.collection.aggregate([
{
$group: {
_id: null,
TotalBalance: {
$sum: "$balance.amount"
}
}
}
])

得到余额 0 而不是 -2300

{ "_id" : null, "TotalBalance" : 0 }

与 $unwind 相同:

db.collection.aggregate([
{ $unwind: "$balance" },
{
$group: {
_id: null,
TotalBalance: { $sum: "$balance.amount" }
}
}
])

我做错了什么?

谢谢

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com