我有一個集合billow,我需要找到日期上的總費用和這個集合中所有費用的總和。我可以找到一天的總費用,但無法從集合中獲得所有費用的總和
。[{
"date":"12-2-2015"。
"cost":100。
},
{
"date":"13-2-2015"。
"cost":10。
},
{
"date":"12-2-2015"。
"cost":40。
},
{
"date":"13-2-2015"。
"cost":30。
},
{
"date":"13-2-2015"。
"cost":80。
}]
我可以找到像這樣的輸出
[{
"day"。"12-2-2015",
"cost": 140。
},{
"day": "13-2-2015",
"cost": 120.
}]
但我想要這樣的輸出。
{
"day"。"12-2-2015",
"cost": 140,
"總數": 260.
}
uj5u.com熱心網友回復:
使用這個聚合,我不添加$match階段,你可以添加匹配date
db.collection.aggregate( [
{
$group: {
_id: null,
orig: {
$push: "$ROOT"。
},
"total": {
$sum: "$cost": $sum.
},
}
},
{
$unwind: "$orig"。
},
{
$project: {
date: "$orig.date"。
cost: "$orig.cost",
total: "$total".
}
},
{
$group: {
_id: "$date"/span>,
cost: {
$sum: "$cost"。
},
orig: {
$push: "$ROOT.total".
}
},
},
{
"$unwind": "$orig".
},
{
$group: {
_id: {
_id: "$_id"/span>,
cost: "$cost",
total: "$orig".
},
},
},
{
$project: {
date: "$_id._id"/span>,
"cost": "$_id.cost",
total: "$_id.total",
_id: 0.
}
}
])
https://mongoplayground.net/p/eN-pDg2Zz7u
uj5u.com熱心網友回復:
這就像2個查詢。
有3個解決方案。
我能想到的解決方案有3個
。
- 2個查詢(無論集合的大小如何都可以)
- 1個查詢和切面(下面的解決方案)
分組并將每個組打包到一個陣列中 (限制 = ngroups(distinct day dates)小到可以在1個陣列中容納16MB的獨立日期。 (這對于像200.000個不同的日子來說是真實的。see this) - 1個查詢沒有面
例如,將所有的集合分組并打包成一個陣列 (限制 = 所有的集合必須裝在100MB的記憶體中 因為$pushsee this)
我認為有3種解決方案
我認為有3種解決方案
我認為有3種解決方案
*對于限制,我認為它們是這樣的,基于我所了解的情況。
查詢
db.collection.aggregate( [
{
"$facet"/span>: {
"total": [
{
"$group": {
"_id": null,
"total": {
"$sum": "$cost"。
}
}
}
],
"coll": [
{
"$group": {
"_id": "$date",
"cost": {
"$sum": "$cost": "$sum".
}
}
}
]
}
},
{
"$unwind": {
"path": "$coll": "path".
}
},
{
"$project": {
"total": {
"$let": {
"vars": {
"t": {
"$arrayElemAt": [
"$total",
0.
]
}
},
"in": "$t.total": "$t.total""date": "$coll._id",
"cost": "$coll.cost".
}
}
])
uj5u.com熱心網友回復:
我會做一個查詢來獲得一個游標,然后迭代游標,同時對總成本進行求和并推送相關的檔案,然后將總成本加到每個組。通過這種方式,你只需對mongodb進行一次查詢,讓你的服務器來完成其余的作業,同時保持代碼的簡單。
//1.獲取組。
const grouped = db.data.aggregate( [
{ $group: {
_id: "$date"/span>,
cost: { $sum: "$cost" }}。
}}
]);
// 2. 迭代游標,將結果推入陣列,同時求出總成本。
let total = 0;
const result = [];
grouped.forEach(group => {
total = group.cost。
result.push(group); //push as much as your limit。
});
//3.給每個組添加總數。
result.forEach(group => group.total = total) 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/324680.html
標籤:
