我有一个订单架构,就像下面的对象代表它一样:
{
"_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 :(得分: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:""}
]
}