Mongodb: Perform a Date range query from the ObjectId in the mongo shell

不想你离开。 提交于 2019-11-27 19:26:41
Kath

You can do that in 2 steps:

 var objIdMin = ObjectId(Math.floor((new Date('1990/10/10'))/1000).toString(16) + "000
0000000000000")
 var objIdMax = ObjectId(Math.floor((new Date('2011/10/22'))/1000).toString(16) + "000
    0000000000000")
 db.myCollection.find({_id:{$gt: objIdMin, $lt: objIdMax}})

or in one step (what is less readable):

db.myCollection.find({_id:{$gt: ObjectId(Math.floor((new Date('1990/10/10'))/1000).toString(16) + "000
    0000000000000"), $lt: ObjectId(Math.floor((new Date('2011/10/10'))/1000).toString(16) + "000
    0000000000000")}})

using mongo shell:

you can use the ObjectId.fromDate built in method:

db.mycollection.find({_id: {$gt: ObjectId.fromDate( new Date('2017-09-23') ) } });

from Node.js driver:

you can use the solution provided by @jksdua here as follows:

db.mycollection.find({_id: {$gt: ObjectID.createFromTime( Date.now()/1000 ) } });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!