[英]Query Mongodb Sum of firsts element of an array of objects
我想為我的數據庫的每個元素編寫一個查詢,用於對數組中第一個 object 的每個字段payment
求和。
架構如下:
var schema = new Schema({
plate : String,
category : String,
brand : String,
model : String,
sign : String,
tax : [{
date : { type: Date, default: Date.now },
payment : { type: Number, default: 0 },
}],
});
我為我的查詢寫了以下 function :
function(callback){
Machine.aggregate(
[
{$unwind: "$tax"},
{$group : {
_id : null ,
tot : { $sum: "$tax.payment"}
}}
]
,callback);
}
但是通過這種方式,我檢索了數組 tax 中所有付款的總和。 我的目標是只取第一個,所以我嘗試使用$tax.0.payment
並使用arrayElemAt: [$tax,0]
但我所有的試驗都給出了 tot = 0。
這里的想法是通過帶有投影的$arrayElemAt
選擇每個payment
數組字段的第一個元素,然后對字段$group
$sum
進行分組求和。
詢問:
db.collection.aggregate([
{
$project: {
firstPayment: {
$arrayElemAt: [
"$tax",
0
]
}
}
},
{
$group: {
_id: null,
PaymentSum: {
$sum: "$firstPayment.payment"
}
}
}
]);
演示 O/P:
[
{
"PaymentSum": 11,
"_id": null
}
]
Machine.aggregate({$unwind:
{path: "$tax"}
},
{$group:{
_id: "$_id",
payment: {$first: "$tax.payment"}
}},
{$group: {
_id: null,
total: {$sum: "$payment"}
}}
)
解釋:
首先我在稅收上使用$unwind
,然后在第一個$group stage
我根據_id對它們進行分組,
這樣我就可以從 unwinded tax 數組中獲得第一筆付款信息。
然后我使用 $sum 將它們添加到第二個$group stage
中。
我用這些數據進行了測試:
機器收集文檔:
{
"_id" : ObjectId("5dbf09a4d7912bcbc61ee9e4"),
"tax" : [
{
"payment" : 10
},
{
"payment" : 20
}
]
},
{
"_id" : ObjectId("5dbf09aad7912bcbc61ee9e5"),
"tax" : [
{
"payment" : 30
},
{
"payment" : 40
}
]
},
{
"_id" : ObjectId("5dbf09afd7912bcbc61ee9e6"),
"tax" : [
{
"payment" : 50
},
{
"payment" : 60
}
]
}
我得到的結果是:
{ "_id" : null, "tot" : 90 }
我希望這能滿足您的要求。
像這樣在你的聚合中添加 $arrayElemAt ..
Machine.aggregate(
[
{$unwind: "$tax"},
{$group : {
_id : null ,
tot : { $sum: { $arrayElemAt : [ "$tax.payment", 0 ]}
}}
]
,callback);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.