mongodb group by date,获取最近的日期

时间:2017-09-20 12:20:59

标签: mongodb

我的“付款”系列中有以下数据:

{
    "_id" : ObjectId("59c2301a31cc7319fcfcc934"),
    "amount" : 243.8016529,
    "payoutDate" : ISODate("2017-09-20T11:20:53.366Z"),     
    "completed" : false,
},
{
    "_id" : ObjectId("59c24e1bbf0e0520702a9136"),
    "amount" : 243.8016529,
    "payoutDate" : ISODate("2017-09-20T11:20:53.366Z"),
    "shopId" : ObjectId("594cb908554baabc7cbc8e88"),
    "completed" : false,
},
{
    "_id" : ObjectId("59c24ea1bf0e0520702a915c"),
    "amount" : 1219.0082645,
    "payoutDate" : ISODate("2017-09-21T11:20:53.366Z"),
    "completed" : false,
},
{
    "_id" : ObjectId("59c24f15bf0e0520702a9216"),
    "amount" : 4876.033058,
    "payoutDate" : ISODate("2017-09-21T11:20:53.366Z"),
    "completed" : false,     
}

如何获得第二天(或今天)completed = false付款的总金额?所以我得到这样的东西?

payoutDate: ISODate("2017-09-20T11:20:53.366Z"),  
totalAmount: 487.6 

totalAmount不必舍入)

编辑:

目前我有这段代码,但它不起作用,因为错误16006:

  

无法从BSON类型字符串转换为日期

但是如果你能看到,我的日期字段已经是ISODate了。

 Payment.aggregate([
      {"$match": {shopId: shop._id}},
      {
       $project: {
                            year: {$year: "payoutDate"},
                            month: {$month: "payoutDate"},
                            dayOfMonth: {$dayOfMonth: "payoutDate"}
                        }
                    },
                       {$group: {
                            _id: {
                                year: '$year',
                                month: '$month',
                                dayOfMonth: '$dayOfMonth'
                            },
                            totalAmount: {$sum: "$amount"},
                            count: {$sum: 1}
                            }
                        },
                        {$sort: {_id: -1}}
                   ]).exec(function(err, payments){
                       console.log(err, payments);
                   })

0 个答案:

没有答案