我有这些日期范围数组。这是我的wep应用程序中的图表功能。
[{
"start": "7/01/2016",
"end": "7/31/2016"
},{
"start": "8/01/2016",
"end": "8/31/2016"
},{
"start": "9/01/2016",
"end": "9/30/2016"
}]
这是我的样本数据。
{
"_id": 68,
"charges": [
{
"id": "ch_1AD2wYHDsLEzoG2tjPo7uGnq",
"amount": 1200,
"created": "7/13/2016"
},{
"id": "ch_1ADPRPHDsLEzoG2t1k3o0qCz",
"amount": 2000,
"created": "8/1/2016"
},{
"id": "ch_1ADluFHDsLEzoG2t608Bppzn",
"amount": 900,
"created": "8/2/2016"
},{
"id": "ch_1AE8OWHDsLEzoG2tBmlm1A22",
"amount": 1800,
"created": "9/14/2016"
}
]
}
这是我试图实现的结果。
[
{
"created": "9/13/2016",
"amount": 1200
},{
"created": "9/14/2016",
"amount": 2900
},{
"created": "9/15/2016",
"amount": 1800
},
]
我可以在没有循环日期范围并查询内部的情况下实现这一目标吗?我只能设法做到这一点
[
{
$match: { _id: 68 }
},{
$unwind: "$charges"
},{
I don't know what to do here
}
]
注意:没关系日期格式
答案 0 :(得分:1)
您可以使用mongodb 3.4中引入的新 $bucket
运算符来实现此目的:
db.collection.aggregate([
{
$match:{
_id:68
}
},
{
$unwind:"$charges"
},
{
$bucket:{
groupBy:"$charges.created",
boundaries:[
"7/01/2016",
"8/01/2016",
"9/01/2016",
"9/30/2016"
],
default:"others",
output:{
amount:{
$sum:"$charges.amount"
}
}
}
}
])
解释:
$match
charges
数组boundaries
中提供)此输出:
{ "_id" : "7/01/2016", "amount" : 1200 }
{ "_id" : "8/01/2016", "amount" : 2900 }
{ "_id" : "9/01/2016", "amount" : 1800 }