Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a collection that looks like this:

{
  _id: ObjectId("50a68673476427844b000001"),
  other fields
}

I want to do a range query to find records between two dates. I know that I can get the date from the ObjectId in the mongo shell var doing this:

var aDate = ObjectId().getTimestamp()

but there isn't a way (as far as I can figure out at the moment) to create an ObjectId consisting of just the timestamp portion - I think my ideal solution is non-functioning mongo shell code would be:

var minDate = ObjectId(new Date("2012-11-10"));
var maxDate = ObjectId(new Date("2012-11-17"));

Use the find with the minDate and MaxDate as the range values.

Is there a way to do this in the SHELL - I'm not interested in some of the driver products.

like image 241
sc28 Avatar asked Nov 27 '12 21:11

sc28


People also ask

What is the use of ObjectId in MongoDB?

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.

What is the type of ObjectId in MongoDB?

Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.

What is MongoDB BSON ObjectId?

The MongoDB\BSON\ObjectId class ¶a 4-byte value representing the seconds since the Unix epoch, a 5-byte random number unique to a machine and process, and. a 3-byte counter, starting with a random value.


2 Answers

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")}})
like image 112
Kath Avatar answered Oct 21 '22 23:10

Kath


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 ) } });
like image 34
Mohammed Essehemy Avatar answered Oct 21 '22 23:10

Mohammed Essehemy