我如何对employeeId进行分组,然后通过paidDate对mongodb进行分组?

时间:2018-03-15 02:38:32

标签: mongodb meteor aggregation-framework

这是我的收藏品数据集

{
"_id" : "001-000001",
"employeeId" : "001-001",   
"paidAmount" : 30,
"paidDate" : ISODate("2017-08-23T14:36:14.410+07:00")
},
{
"_id" : "001-000004",   
"employeeId" : "001-001",   
"paidAmount" : 10,
"paidDate" : ISODate("2017-08-23T06:45:29.497+07:00"),  
},
{
"_id" : "001-000005",   
"employeeId" : "001-001",   
"paidAmount" : 15,
"paidDate" : ISODate("2017-08-01T06:45:29.497+07:00"),  
},
{
"_id" : "001-000002",
"employeeId" : "001-002",   
"paidAmount" : 15,
"paidDate" : ISODate("2017-08-01T12:49:08.724+07:00")   
},
{
"_id" : "001-000003",   
"employeeId" : "001-002",   
"paidAmount" : 15,
"paidDate" : ISODate("2017-08-01T06:45:29.497+07:00"),  
},    

我想得到这样的结果请帮帮我

{
"_id" : "001-004",
"paidAmount" : 45,  
"employeeId" : "001-001",
"item" : [
    [
        {
            "paidDate" : ISODate("2017-08-23T14:36:14.410+07:00")
            "paidAmount" : 30
        },
        {
            "paidDate" : ISODate("2017-08-01T06:45:29.497+07:00"),  
            "paidAmount" : 15
        },

    ]
  ]
},
{
"_id" : "001-004",
"paidAmount" : 30,  
"employeeId" : "001-002",
"item" : [
    [
        {
            "paidDate" : ISODate("2017-08-01T12:49:08.724+07:00")
            "paidAmount" : 30
        }       
    ]
  ]
},

2 个答案:

答案 0 :(得分:0)

您可以尝试以下聚合。

db.collection.aggregate([
  {"$group":{
    "_id":{"employeeId":"$employeeId","paidDate":"$paidDate"},
    "paidAmount":{"$sum":"$paidAmount"}
  }},
  {"$group":{
    "_id":{"employeeId":"$_id.employeeId"},
    "paidAmount":{"$sum":"$paidAmount"},
    "item":{"$push":{"paidDate":"$_id.paidDate","paidAmount":"$paidAmount"}}
  }},
  {"$project":{
    "_id":0,
    "paidAmount":1,
    "employeeId":"$_id",
    "item":1
  }}
])

答案 1 :(得分:0)

如果您想要发布复合集合,可能需要查看meteor-publish-composite插件。它允许您发布复合集合。但它只适用于服务器。