我們有一個聚合查詢投影幾個子文檔。我們希望對這些計劃值應用一些算術運算,如Sum和Product。用於算術運算的MongoDB聚合 - 子文檔字段
聚集查詢 -
Item.aggregate([
{ $unwind: '$dummy'},
{ $match: {'dummy.storage': {$gt: 0}} },
{ $group: {_id: '$_id',
dummy: {$push: '$dummy'},
original_y: { $first: "$original_y" },
new_y: { $first: "$new_y" },
}},
{$project:{
original_y: 1, new_y: 1,
tallyAmount: {$sum: ["$new_y","$original_y"] }
}
},
]
)
.exec(function(err, results){
if(err)
{
console.log("Error : " + err);
return res.json ({error: "Error"});
}
else if(!(results) || results == null || results.length == 0)
{
console.log("No Results Found");
return res.json ({error: "No Results Today"});
}else{
res.send(results);
}
});
這給出了一個錯誤,說明 invalid operator '$sum'
我們應該做些什麼來獲得original_y
和new_y
在$project
總和?
EDIT
文件:
{
id:1,
original_y: 200,
new_y: 140,
dummy: [
{id:1, storage:2, cost: 10},
{id:2, storage:0, cost: 20},
{id:3, storage:5, cost: 30},
]
}
產出預期:
{
id:1,
original_y: 200,
new_y: 140,
dummy: [
{id:1, storage:2, cost: 10, tallyAmount: 34},
{id:3, storage:5, cost: 30, tallyAmount: 11.33},
]
}
其中, tallyAmount = (original_y + new_y)/cost
ERROR:不能用於子添加表達式因爲已經有一個表達式適用於整個字段
@chridam已更新文檔和預期輸出 –
感謝您的更新,我已在下面更新了我的答案以包含更改。 – chridam