我正在try 在聚合管道内的一个对象中将两个金额相加.
这是我的Sandbox :https://mongoplayground.net/p/LIvksL-UGur
文档:
[
{
"result": {
"invoices": [
{
"product": "baseball",
"amount": 4,
"tax": 1
},
{
"product": "basketball",
"amount": 10,
"tax": 2
}
]
}
}
]
我希望结果是:
[
{
"result": {
"invoices": [
{
"product": "baseball",
"amount": 4,
"tax": 1,
"total": 5
},
{
"product": "basketball",
"amount": 10,
"tax": 2,
"total": 12
}
]
}
}
]
我觉得应该这样:
db.collection.aggregate([
{
$set: {
"result.invoices": {
"total": "$result.invoices.amount + $result.invoices.tax"
}
}
}
])
总数为空,因为它试图添加两个数组,我通过try 以下命令来理解这一点:
db.collection.aggregate([
{
$set: {
"result.invoices": {
"total": "$result.invoices.amount"
}
}
}
])
...这给了我们这个机会:
[
{
"result": {
"invoices": [
{
"product": "baseball",
"amount": 4,
"tax": 1,
"total": [
4,
10
]
},
{
"product": "basketball",
"amount": 10,
"tax": 2,
"total": [
4,
10
]
}
]
}
}
]
我怎样才能以正确的方式go 做呢?
注:我意识到这是一个非常简单的例子,我可以在得到结果后添加计算.这只是说明了我正在努力解决的一个更复杂的问题.