mongodb最近七天的数据总和数据需要日期对象

时间:2018-06-20 10:25:28

标签: javascript node.js mongodb

我试图查找最近7天记录的按天总数。但我无法获得正确的日期对象。

示例代码

 db.collection('history').aggregate([
                               {$match:{ts:{$gt: moment().subtract(6, 'days').startOf('day')._d,$lt: moment().endOf('day')._d}}},
                    { $group: {
                            _id : { day: { $dayOfMonth: "$ts" }, 
                                 month: { $month: "$ts" },
                                year: { $year: "$ts" } },
                            EGeneration: { '$sum': '$EGeneration' },
                            EConsumption: { '$sum': '$EConsumption' }
                        }
                    }
                ], function (err, datas) {
                    if (err || !datas) console.log(err);
                    else {
                        console.log(datas);
                    }
                })

,因为_id我需要正确的日期对象

样本数据

{
"_id" : {
    "deviceId" : 20016,
    "ts" : ISODate("2018-06-08T09:58:37.000Z")
},
"ts" : ISODate("2018-06-08T09:58:37.000Z"),
"EGeneration" : 0.00092393,
"EConsumption" : 0

}

{     “_ID” : {         “ deviceId”:20019,         “ ts”:ISODate(“ 2018-06-09T09:58:37.000Z”)     },     “ ts”:ISODate(“ 2018-06-09T09:58:37.000Z”),

"EGeneration" : 0.00092393,
"EConsumption" : 0

}

{     “_ID” : {         “ deviceId”:20028,         “ ts”:ISODate(“ 2018-06-09T09:58:37.000Z”)     },     “ ts”:ISODate(“ 2018-06-09T09:58:37.000Z”),

"EGeneration" : 0.00092393,
"EConsumption" : 0

}

样本输出

[ { _id: { day: 9, month: 6, year: 2018 },
EGeneration: 0.00184786,
EConsumption: 0 },

{_id:{天:8,月:6,年:2018},     产生:0.00092393,     消耗量:0}]

1 个答案:

答案 0 :(得分:0)

要获得ISODate格式的最终​​输出,请将ISODate转换为字符串,以除去时间部分。将日期以字符串形式转换为ISODate,然后进行聚合

db.history.aggregate([
   {$project:{"timestamp":"$ts","gen":"$EGeneration","con":"$EConsumption",diff_msecs:{$subtract:[new ISODate(),"$ts"]}}},
   {$project:{"timestamp":1,"con":1,"gen":1,diff_days:{$divide:["$diff_msecs",1000*60*60*24]}}},
   {$match:{"diff_days":{"$lte":7}}},
   {"$project":{"con":1,"gen":1,"dateString":{$dateToString: { format: "%Y-%m-%d", date: "$timestamp" }}}},
   {"$project":{"_id":0,"con":1,"gen":1,"datewithouttime":{"$dateFromString":{"dateString": "$dateString"}}}},
   {"$group":{"_id":"$datewithouttime","EGeneration":{"$sum":"$gen"},"EConsumption":{"$sum":"$con"}}}])

输出为:

{ "_id" : ISODate("2018-06-09T00:00:00Z"), "EGeneration" : 0.00184786, "EConsumption" : 0 }
{ "_id" : ISODate("2018-06-08T00:00:00Z"), "EGeneration" : 0.00092393, "EConsumption" : 0 }