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)
})
@dsncode
Copy link

dsncode commented Oct 30, 2014

nice! just what I was searching for!
thumbs up!

@iBet7o
Copy link

iBet7o commented Aug 28, 2015

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

@ayushgp
Copy link

ayushgp commented Oct 18, 2015

Is there a way to find documents that were created between a week ago and right now?

@naveencasp
Copy link

how can i define Timestamp ? in mongoose

@duuz
Copy link

duuz commented Apr 28, 2016

in mongoose type:Date.
on Schema do this
ex.: entry_date:{type:Date}

@Manishchauhan1
Copy link

Manishchauhan1 commented Jun 22, 2016

is there a way to search records from mongo db collection before one hour from its actual flight time ?

@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