Anubhav
Anubhav

Reputation: 1625

Query a Timestamp in MongoDB

MongoDB document sample is given below:

{
    "_id" : ObjectId("5f2df113bdde22f1043g45gg"),
    "cd" : 1395376406,
    "dob" : 552026006,
    "e" : "[email protected]",
    "g" : "M"   
}

I need query to get birthday list for today using dob(date of birth) field(timestamp).

Thanks in advance!

Upvotes: 1

Views: 1002

Answers (2)

BatScream
BatScream

Reputation: 19700

Since MongoDb doesn't have any inbuilt functions/operations to support parsing raw timestamps and extracting information from them, you need to do the operation by passing a custom java script function to the server and get it executed there. This function would be executed for each record though.

db.collection.find({$where:function(){
      var recDate = new Date(this.dob);
      var recDay = recDate.getDate();
      var recMonth = recDate.getMonth();

      var today = new Date();
      var todayDate = today.getDate();
      var todayMonth = today.getMonth();

    return (recDay == todayDate && recMonth == todayMonth);
}});

The function simply checks if any record's day and month match today's day and month. Although this works for timestamps, you should take advantage of MongoDBs ISODate data type whenever you store date information. This enables us to use various operators and functions on these fields. Moreover they would be faster. If your document had the below structure:

{
    "_id" : "1",
    "cd" : 1395376406,
    "dob" : ISODate("2014-11-19T08:00:00Z"),
    "e" : "[email protected]",
    "g" : "M"   
}

Where, the dob field is of ISODate type. You could easily do a aggregate operation to fetch the results.

var todayDate = ISODate().getDate();
var todayMonth = ISODate().getMonth();

db.collection.aggregate([
{$project:{"day":{$dayOfMonth:"$dob"},
           "month":{$month:"$dob"},
           "_id":1,"cd":1,"dob":1,"e":1,"g":1}},
{$match:{"day":todayDate,"month":todayMonth}},
{$project:{"cd":1,"dob":1,"e":1,"g":1,"_id":1}}
])

The above operation utilizes the functions and operations that are allowed on a ISODate field. Querying becomes a lot easier and better.

Upvotes: 1

Amit Dubey
Amit Dubey

Reputation: 11

I am not sure how elegant my solution is, but it should work

var start = new Date();
start.setHours(0,0,0,0);

var end = new Date();
end.setHours(23,59,59,999);

db.collection.find({dob:{$gt:start.getTime(), $lt:end.getTime()}})

Upvotes: 1

Related Questions