【问题标题】:Mongodb- Query documents between two timestampMongodb-在两个时间戳之间查询文档
【发布时间】:2019-08-08 03:18:16
【问题描述】:

我有以下结构的文档:

{
"escalation" : null,
"reclassified" : false,
"timestamp" : "1559164897437",
"endFlow" : "false",
"channel" : "web",
"intents" : null
},
{
"escalation" : null,
"reclassified" : false,
"timestamp" : "1565196671234",
"endFlow" : "true",
"channel" : "web",
"intents" : null
}  

我想在两个时间戳之间查询上述文档,例如“1559254897437”和“1563996671234”。
请注意,我将时间戳字段的值存储为字符串,而不是整数。

我尝试过的:

db.getCollection('messagelogs').find({
    'timestamp':{
        $lte:1559164897437,
        $gte:1560351891811}
        })

不幸的是,这将返回所有文档。

在两个时间戳之间获取文档的正确查询是什么?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    由于时间戳在 DB 中以字符串形式存在,我们需要在字符串范围内查询它,而不是数字。以下查询可以获得预期的输出:

    db.getCollection('messagelogs').find(
    {
        'timestamp':{
            $gte:'1559164897437',
            $lte:'1560351891811'
        }
    })
    

    输出:

    {
        "_id" : ObjectId("5d4b1ccdcbfa696dcd9924a3"),
        "escalation" : null,
        "reclassified" : false,
        "timestamp" : "1559164897437",
        "endFlow" : "false",
        "channel" : "web",
        "intents" : null
    }
    

    【讨论】:

      【解决方案2】:

      基本上您正在尝试对每个文档进行类似于 AND 操作的操作,表示您需要一个具有时间戳 $lte 时间戳和同时 $gte 不同时间戳的文档,而不是您需要执行 OR 来获取外部边界,即;如果任何一个条件匹配,请带出文件,请这样做:

      db.getCollection('messagelogs').find({$or: [{'timestamp': {$lte:'1559164897437'}}, {'timestamp': {$gte:'1560351891811'}}] })
      

      假设您犯了一个错误,如果您在特定时间之间需要文档,则需要交换您的时间戳:

      db.getCollection('messagelogs').find({$and: [{'timestamp': {$lte:'1560351891811'}}, {'timestamp': {$gte:'1559164897437'}}] })
      

      或者简单地说:

      db.getCollection('messagelogs').find({'timestamp': {$gte:'1559164897437', $lte: '1560351891811'}})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-14
        • 2014-01-28
        • 2020-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        • 1970-01-01
        相关资源
        最近更新 更多