我想按月和年份获取一组mongo文档。我当前的查询有效:
var query = Order.aggregate(
{
$project:
{
cust_ID : '$request.headers.custID',
cost : '$request.body.expectedPrice',
year :
{
$year: '$date'
},
month:
{
$month: '$date'
}
}
},
{
$match:
{
year : year,
month: month
}
}
);
但我还需要按客户ID汇总/推送总订单,因此我将其添加到$project
和$match
之间的查询的中间阶段。查询返回为空,即使我知道有结果:
{
$group:
{
"_id": "$request.headers.custID",
"custID" : {
"$first" : "$request.headers.custID"
},
"orders":
{
"$push":
{
"order": "$request.body"
}
}
}
},
我会将此聚合器push
添加到$ project,但$ project不支持。我该如何撰写此查询?
答案 0 :(得分:0)
由于您通过 $project
管道获得了新字段,因此您应该将它们传递到定义的下一个管道步骤:
var pipeline = [
{
"$project": {
cust_ID: '$request.headers.custID',
"cost": '$request.body.expectedPrice',
"year": { "$year": '$date' },
"month": { "$month": '$date' },
"order": "request.body"
}
},
{
"$match": {
"year": year,
"month": month
}
},
{
"$group": {
"_id": "$cust_ID",
"custID": { "$first" : "$cust_ID" },
"cost": { "$first" : "$cost" },
"orders": { "$push": "$order" }
}
},
]
var query = Order.aggregate(pipeline)