Date Range Query on ObjectId in MongoDB

Connect with

MongoDB
How to write a date range query on _id (objectId) in mongodb? This is very easy as MongoDB by default keep one primary key which is _id , if you not provide while inserting/adding. In _id key mongoDB keep date time or you can say timestamp of the system when inserted in to mongoDB. You can query on ObjectId or _id of mongoDB either greater than ($gt) or less than date ($lt). Here you can provide any one of them or both, it’s your choice based on the requirement. I would recommend not to keep separate field which keeps for dateTime / timestamp. _id is sufficient to pull based on date range.

Add Documents

For demonstrating purpose, first add few documents and then proceed further which help to learn.

db.user.insert({_id: ObjectId("54a440a80000000000000000"), "name":"ranjeet", "age":23, "ques": "objectId and mongoDB"});
db.user.insert({_id: ObjectId("54cd1f280000000000000000"), "name":"rob", "age":44, "ques": "query on objectId "});
db.user.insert({_id: ObjectId("54f209280000000000000000"), "name":"simmon", "age":40, "ques": "how to getTimeStamp from mongoDB"});
db.user.insert({_id: ObjectId("551ae7a80000000000000000"),"name":"jha", "age":30, "ques": "manipulation of objectId "});

Get Added documents

Pull the added documents by following query.

> db.user.find();
{ "_id" : ObjectId("54a440a80000000000000000"), "name" : "ranjeet", "age" : 23, "ques" : "objectId and mongoDB" }
{ "_id" : ObjectId("54cd1f280000000000000000"), "name" : "rob", "age" : 44, "ques" : "query on objectId " }
{ "_id" : ObjectId("54f209280000000000000000"), "name" : "simmon", "age" : 40, "ques" : "how to getTimeStamp from mongoDB" }
{ "_id" : ObjectId("551ae7a80000000000000000"), "name" : "jha", "age" : 30, "ques" : "manipulation of objectId " }

Print ISODate of Documents

db.user.find({}).forEach(function(doc) {
   var ts= doc._id.getTimestamp();
    printjson(ts);
})

Output

> db.getCollection('user').find({}).forEach(function(doc) {
...    var ts= doc._id.getTimestamp();
...     printjson(ts);
... });
ISODate("2014-12-31T18:30:00Z")
ISODate("2015-01-31T18:30:00Z")
ISODate("2015-02-28T18:30:00Z")
ISODate("2015-03-31T18:30:00Z")

Query between two dates on _id

var idMin = ObjectId(Math.floor((new Date('2015/1/31'))/1000).toString(16) + "0000000000000000")
var idMax = ObjectId(Math.floor((new Date('2016/4/5'))/1000).toString(16) + "0000000000000000")
db.user.find({_id:{$gt: idMin, $lt: idMax}}).pretty()

Output

> var idMin = ObjectId(Math.floor((new Date('2015/1/31'))/1000).toString(16) + "0000000000000000")
> var idMax = ObjectId(Math.floor((new Date('2016/4/5'))/1000).toString(16) + "0000000000000000")
> db.user.find({_id:{$gt: idMin, $lt: idMax}}).pretty()
{
        "_id" : ObjectId("54cd1f280000000000000000"),
        "name" : "rob",
        "age" : 44,
        "ques" : "query on objectId "
}
{
        "_id" : ObjectId("54f209280000000000000000"),
        "name" : "simmon",
        "age" : 40,
        "ques" : "how to getTimeStamp from mongoDB"
}
{
        "_id" : ObjectId("551ae7a80000000000000000"),
        "name" : "jha",
        "age" : 30,
        "ques" : "manipulation of objectId "
}

Drop the database

> use userdemo
switched to db userdemo
> db.dropDatabase()
{ "dropped" : "userdemo", "ok" : 1 }

Reference

MongoDB doc

Write your comments or suggestions to improve this post.


Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *