Date Range Query on ObjectId in MongoDB

Connect with

Date Range Query on ObjectId in MongoDBHow to write a date range query on ObjectId in MongoDB or date range query on _id in MongoDB? You can query on ObjectId or _id of MongoDB either greater than ($gt) or less than date ($lt).

1. Overview of Date Range query on ObjectId or _id in MongoDB

Most of the time we keep the default value in _id in MongoDB, which is the primary key in MongoDB. This is very easy as MongoDB by default keeps one primary key which is _id. In _id key, MongoDB keep date-time or timestamp of the system when inserted into 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 a separate field for DateTime / timestamp. _id is sufficient to pull based on a date range.

2. 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 "});

3. 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 " }

4. Print ISODate of Documents

print ISODate of document while fetching by query.

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")

5. 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 "
}

6. Drop the database

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

7. Reference

MongoDB docs

Thanks for visiting this post for date range query on ObjectId or _id in MongoDB. You can also visit MongoDB Tutorial Listing page for more articles on MongoDB document-oriented database.
Write your comments or suggestions to improve this post. Happy Learning! 🙂


Connect with

Leave a Comment

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