GroupBy和过滤与聚合

我有一个订单架构,像下面的对象代表它:

{ "_id" : ObjectId("59dce1fa2d57920d3e62bdf3"), "updatedAt" : ISODate("2017-10-10T15:06:34.205+0000"), "createdAt" : ISODate("2017-10-10T15:06:34.128+0000"), "_customer" : ObjectId("59dce1f92d57920d3e62bd44"), "_distributor" : ObjectId("59dce1f92d57920d3e62bd39"), "status" : "NEW", } 

现在我想分组和过滤它。 通过相同的_customer分组,并使用createdAt字段进行过滤。 如何使用聚合来处理这两个?

尝试下面的代码使用$match$group$project

 Orders.aggregate([ {$match : { createdAt : "<your createdAt value here>"}}, {$group : { _id : { _id : "$_customer" }, data : { $addToSet : { _id : "$_id" , updatedAt : "$updatedAt" , createdAt : "$createdAt" , _distributor : "$_distributor" , status : "$status"} } }}, { $project : { _id : "$_id._id", data: 1 }} ]) 

这将为您提供以下结构中的文档,并将仅添加基于createdAt的过滤logging

 { _id : "customer 1", data : [ { _id : "" , updatedAt : "" , createdAt : "" , _distributor : "" , status:""}, { _id : "" , updatedAt : "" , createdAt : "" , _distributor : "" , status:""} ] }, { _id : "customer 2", data : [ { _id : "" , updatedAt : "" , createdAt : "" , _distributor : "" , status:""}, { _id : "" , updatedAt : "" , createdAt : "" , _distributor : "" , status:""}, { _id : "" , updatedAt : "" , createdAt : "" , _distributor : "" , status:""} ] }