MongoDB Compass:按日期过滤和查询

问题描述 投票:0回答:2

假设我有一个包含多个文档的旅行收藏,

比如

{
    "_id": {
        "$oid": "27637b4h6u7y897ba9021bn2"
    },
    "startTime": {
        "$date": "2021-05-04T13:55:38.286Z"
    }
    "stopTime": {
         "$date": "2021-05-04T11:55:38.286Z"
    }
}

{
    "_id": {
        "$oid": "2532b4h6u7y897ba9021bn2"
    },
    "startTime": {
        "$date": "2021-05-04T12:55:38.286Z"
    }
    "stopTime": {
         "$date": "2021-05-04T11:55:38.286Z"
    }
}

我应该写什么查询,在 mongoCompass 如果可能的话,来检索:

  • 超过1小时的行程次数?
mongodb mongodb-query mongodb-compass
2个回答
3
投票

您可以使用以下聚合代码:

[{$addFields: {
  travelTime: {$abs:{$subtract:[{ $toLong:'$stopTime'},{ $toLong:'$startTime'}]}}
}}, {$match: {
  travelTime:{$gt:3600000}
}}, {}]

这里我们以毫秒为单位获取绝对时间差,并检查它是否大于一小时(3600000)


0
投票
use this date format with greater than (gte) and less than(lt)->
   {
    $gte:ISODate("2020-03-01"),
    $lt:ISODate("2021-03-31")
    }
    example->
    
    {
    type: "test",
    status: "Success",
    createdTime:{$gte: '2023-05-10'}
    }

Here type,status and createdTime are fields where createdTime is a date field 
and we are filtering based on type, status and createdTime greater that a specific date.
© www.soinside.com 2019 - 2024. All rights reserved.