按日期对customerID的唯一记录进行分组并跟踪customerID的总记录

时间:2016-01-29 16:24:42

标签: mongodb

我想按月和年份获取一组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不支持。我该如何撰写此查询?

1 个答案:

答案 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)