Skip to content

Instantly share code, notes, and snippets.

@guilleferrer
Created January 24, 2012 11:50
Show Gist options
  • Save guilleferrer/1669783 to your computer and use it in GitHub Desktop.
Save guilleferrer/1669783 to your computer and use it in GitHub Desktop.
Query for a date range using Mongo Timestamps
db.Collection.find({
created_at : {
'$gte': new Timestamp(new Date(2012, 0, 21), 0),
'$lte': new Timestamp(new Date(2012, 0, 22), 0)
})
@csmith0651
Copy link

Don't think this is right. I think you need to getTime() and then divide by 1000:

db.Collection.find({
 created_at : {
    '$gte': new Timestamp((new Date(2012, 0, 21)).getTime()/1000, 0),
    '$lte': new Timestamp((new Date(2012, 0, 22)).getTime()/1000, 0)
})

@belide
Copy link

belide commented Aug 1, 2018

I have a problem here!

Let us say I have two date attributes in object like below (fromDate and toDate)

{ "_id" : ObjectId("5b6177ae5c9f723dc414f53f"), "employeeName" : "Sridhar Bellide", "employeeId" : "823284", "fromDate" : ISODate("2018-08-10T00:00:00Z"), "toDate" : ISODate("2018-08-20T00:00:00Z"), "team" : "Game of Rules", "leaveType" : "Casual", "__v" : 0 }

So, inserted dates are fromDate is 10 Aug and toDate is 20 Aug.

My question is if I have input like fromDate selected as 8 Aug and endDate selected as 15 Aug, I want that object to be extracted from MongoDB.

What query I need to use for this? please help!

Thanks & Regards,
Sridhar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment