GroupBy并使用聚合进行过滤

时间:2017-10-15 13:42:57

标签: javascript node.js mongodb express mongoose

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

{ 
    "_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来处理这两个?

1 个答案:

答案 0 :(得分: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:""}
   ]
}