mongodb在时间段内获得价值总和

时间:2017-08-11 08:09:01

标签: node.js mongodb

我正在尝试查找在特定时间段内创建的一些记录。 然后我想计算这些记录的值的总和。

{"member_id":"3755","value":184607,"create_time":"2017-8-11 10:36:58"
{"member_id":"3234","value":74582,"create_time":"2017-8-11 10:36:58",
{"member_id":"4857","value":36776,"create_time":"2017-8-11 10:36:58",
{"member_id":"2042","value":15753,"create_time":"2017-8-11 10:36:58",
{"member_id":"1374","value":655103,"create_time":"2017-8-11 10:36:59"
{"member_id":"3777","value":595437,"create_time":"2017-8-11 10:36:59"
{"member_id":"5271","value":306364,"create_time":"2017-8-11 10:36:59"
{"member_id":"2143","value":164831,"create_time":"2017-8-11 10:36:59"
{"member_id":"1374","value":655103,"create_time":"2017-8-11 10:36:59"
{"member_id":"3777","value":595437,"create_time":"2017-8-11 10:36:59"
{"member_id":"5271","value":306364,"create_time":"2017-8-12 10:36:59"
{"member_id":"2143","value":164831,"create_time":"2017-8-12 11:28:59"
{"member_id":"3777","value":595437,"create_time":"2017-8-12 14:46:59"
{"member_id":"5271","value":306364,"create_time":"2017-8-13 11:36:59"
{"member_id":"2143","value":164831,"create_time":"2017-8-13 13:36:59"
...

以下是获取价值总和的代码,如何获得2017-8-11 10:36:00和2017-8-12 14:00:00之间的价值总和

  connection.aggregate([{
                $match: match
            },
            {
                $group: {
                    _id: null,
                    total: {
                        $sum: "$value"
                    }
                }
            }
        ], function(err, result) {
            if (err) throw (err);
            result = {
                member_id: member_id,
                total: result[0].total,
            }
            cb(result);
        });

1 个答案:

答案 0 :(得分:1)

let todayDate = new Date();
let beforeDate = new Date();
beforeDate.setDate(beforeDate.getDate() - 15); // 15 is days
db.collections.aggregate([
    {
        "$match":
            {
                "insertDate":
                    {
                        "$lte": todayDate,
                        "$gte": beforeDate
                    }
            }
    }
])
.exec()
.then((result) => {
    //result
})
.catch((err) => {
    // error
});