美文网首页mongodb
【mongoDB】mongoDB根据时间范围查询数据

【mongoDB】mongoDB根据时间范围查询数据

作者: Bogon | 来源:发表于2022-05-29 00:16 被阅读0次

MongoDB条件对应关系:

(>) 大于 - $gt
(<) 小于 - $lt
(>=) 大于等于 - $gte
(<= ) 小于等于 - $lte
Date()     显示当前的时间
new Date   构建一个格林尼治时间   可以看到正好和Date()相差8小时,我们是+8时区,也就是时差相差8,所以+8小时就是系统当前时间
ISODate()   格林尼治时间

MongoDB 日期查询目前可通过Date 和ISODate两种方式:

1.Date方式

查询ct>=2012.12.7 且et<=2012.12.7

"ct":{$gte:new Date(2012,11,7)},"et":{$lte:new Date(2012,11,7)}

查询日期大于等于2016年12月1日的记录条数(注意中间的月份写11,就是12月)

db.xxx.find({"ct":{$gte:new Date(2016,11,1)}})

2.ISODate方式

ISODate("2016-01-01T00:00:00Z")

ISODate("2021-06-03T20:57:00.00Z"),是一个标准时间格式,表示格林尼治时间

db.xxxx.find({"ct":{"$gt":ISODate("2017-04-20T01:16:33.303Z")}}) // 大于某个时间

db.xxxx.find({"ct":{"$lt":ISODate("2017-04-20T01:16:33.303Z")}}) // 小于某个时间

db.xxxx.find({"$and":[{"ct":{"$gt":ISODate("2017-04-20T01:16:33.303Z")}},{"ct":{"$lt":ISODate("2018-12-05T01:16:33.303Z")}}]}) // 某个时间段

db.xxxx.find({"ct":{"$gte":ISODate("2017-04-20T01:16:33.303Z"),"$lte":ISODate("2018-12-05T01:16:33.303Z")}})  //某个时间段

db.xxx.find({"createTime":{"$gt":ISODate("2021-06-03T20:57:00.00Z"),"$lt":ISODate("2021-06-03T20:59:00.00Z")}})  //某个时间段

从mongoDB的testDB库的testCol表里查询 userName为Bogon,从 xx到xx时间段内的数据

use  testDB

db.testCol.find( {"$and":[{"userName" : "Bogon"},{"date":{"$gt": ISODate("2022-04-25T00:00:00Z")}},{"date":{"$lt": ISODate("2022-05-27T00:00:00Z")}}]})

mongoexport   \
-h xx.xx.xx.xx \
--port=27017  \
--username=user \
--password=XXX    \
--authenticationDatabase=admin  \
-d  testDB  \
-c T_testCol  \
-q '{"$and":[{"time":{"$gt": new Date(1626307200000)}},{"time":{"$lt": new Date(1626534000000)}}]}'   \
--type  json  \
-o T_testCol.json
use testDB
db.testCol.find({"refURL": {$exists: true}, "contentType" : "image/png", "expireDate": {$exists: true}, "expireDate" : {$ne :ISODate("2121-12-11T16:00:00Z")}}).sort({"expireDate": -1}).limit(5).pretty()

参考

在 MongoDB 中返回基于日期的查询
https://www.delftstack.com/zh/howto/mongodb/return-query-based-on-date-in-mongodb

mongoDB Date 之坑探究
https://huangzhw.github.io/2017/10/22/mongodb-date/

相关文章

网友评论

    本文标题:【mongoDB】mongoDB根据时间范围查询数据

    本文链接:https://www.haomeiwen.com/subject/xgbmprtx.html