2017-10-15 68 views
0

滤波器我有一个订单模式其中类似下面对象表示它:的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字段。如何使用Aggregation来处理这两个问题?

+0

你的问题筛选的记录是广泛的。但请按照使用[$ group](https://docs.mongodb.com/manual/reference/operator/aggregation/group/)的汇总文档,然后可能[$ match](https://docs.mongodb.com/manual/reference/operator/aggregation/match /)来过滤。 – Mikey

回答

0

尝试以下使用$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

{ 
    _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:""} 
    ] 
}