获取MongoDB中两个日期的持续时间

时间:2019-10-04 13:28:46

标签: mongodb

我正在尝试在MongoDB中执行查询,两个日期之间的持续时间 可以说

** startTime:ISODate('2019-09-17 20:15:00.000'),         endTime:ISODate('2019-09-17 20:55:00.000')**

我希望lastSeen-firstSeen作为输出中的持续时间

以下是IM正在执行的查询


db.TN_Collection.aggregate([
        {$match: {DE:{$in:devices},'T':{$gt: ISODate('2019-09-15 21:45:00.000'), $lt: ISODate('2019-09-15 22:25:00.000')}}},
        {$group: {_id: {A: '$A', DE: '$DE'}, firstSeen:{$min:'$T'}, lastSeen: {$max: '$T'}}}
])
.forEach(function(msg) {print(msg._id.A +',' + msg._id.DE+',' + msg.firstSeen+',' + msg.lastSeen)})


1 个答案:

答案 0 :(得分:0)

以下查询可以为我们提供预期的输出:

db.TN_Collection.aggregate([
    {
        $match:{
            "DE":{
                $in:["76612"]
            },
            "T":{
                $gte:ISODate('2019-09-11 07:20:55.298'),
                $lte:ISODate('2019-09-15 22:25:00.000')
            }
        }   
    },
    {
        $group:{
            "_id":{
                "A":"$A",
                "DE":"$DE"
            },
            "firstSeen":{
                $min:"$T"
            },
            "lastSeen":{
                $max:"$T"
            }
        }
    },
    {
        $project:{
            "_id":0,
            "A":"$_id.A",
            "DE":"$_id.DE",
            "Duration":{
                $divide:[
                    {
                        $subtract:[
                            "$lastSeen",
                            "$firstSeen"
                        ]
                    },
                    60000
                ]
            }
        }
    }
]).pretty()

数据集:

{
    "_id" : ObjectId("5d9b306b711a1e3a8167c712"),
    "DE" : "76612",
    "A" : "00101219",
    "T" : ISODate("2019-09-11T07:20:55.298Z"),
    "R" : -58
}
{
    "_id" : ObjectId("5d9b306b711a1e3a8167c713"),
    "DE" : "76612",
    "A" : "00101208",
    "T" : ISODate("2019-09-11T07:20:55.298Z"),
    "R" : -64
}
{
    "_id" : ObjectId("5d9b306b711a1e3a8167c714"),
    "DE" : "76612",
    "A" : "00100005",
    "T" : ISODate("2019-09-11T07:20:55.298Z"),
    "R" : -70
}
{
    "_id" : ObjectId("5d9b306b711a1e3a8167c715"),
    "DE" : "76612",
    "A" : "00101219",
    "T" : ISODate("2019-09-12T07:20:55.298Z"),
    "R" : -58
}
{
    "_id" : ObjectId("5d9b306b711a1e3a8167c716"),
    "DE" : "76612",
    "A" : "00101208",
    "T" : ISODate("2019-09-13T07:20:55.298Z"),
    "R" : -64
}
{
    "_id" : ObjectId("5d9b306b711a1e3a8167c717"),
    "DE" : "76612",
    "A" : "00100005",
    "T" : ISODate("2019-09-14T07:20:55.298Z"),
    "R" : -70
}

输出:

{ "A" : "00100005", "DE" : "76612", "Duration" : 4320 }
{ "A" : "00101208", "DE" : "76612", "Duration" : 2880 }
{ "A" : "00101219", "DE" : "76612", "Duration" : 1440 }