如果您事先知道金額字段,那麼您可以在單個聚合操作中動態創建管道。
看看下面的演示:
var amountFields = ["amount", "totalAmount", "cashbackAmount", "unitPrice"],
groupOperator = { "$group": { "_id": "$siteid" } };
amountFields.forEach(function (field){
groupOperator["$group"][field+"Total"] = { "$sum": "$"+field };
groupOperator["$group"][field+"Count"] = {
"$sum": {
"$cond": [ { "$gt": [ "$"+field, null ] }, 1, 0 ]
}
};
});
db.test.aggregate([groupOperator]);
填充測試文件
db.test.insert([
{
"siteid": "123456",
"amount": 1.32
},
{
"siteid": "123456",
"cashbackAmount": 8.32
},
{
"siteid": "123456",
"cashbackAmount": 9.74
},
{
"siteid": "123456",
"unitPrice": 0.19
},
{
"siteid": "123456",
"amount": 27.8,
"totalAmount": 15.22,
"unitPrice": 5.10,
"cashbackAmount": 43.62
},
{
"siteid": "123456",
"unitPrice": 5.07
},
{
"siteid": "123456",
"amount": 12.98,
"totalAmount": 32.82
},
{
"siteid": "123456",
"amount": 6.65,
"unitPrice": 5.10
}
])
樣品聚集輸出
{
"_id" : "123456",
"amountTotal" : 48.75,
"amountCount" : 4,
"totalAmountTotal" : 48.04,
"totalAmountCount" : 2,
"cashbackAmountTotal" : 61.68,
"cashbackAmountCount" : 3,
"unitPriceTotal" : 15.46,
"unitPriceCount" : 4
}
你是什麼意思'獲取每個數量字段存在的數字次數?你能給出一些預期的輸出例子嗎? – Shrabanee