2

Hi Guys I am trying to write a complex query in mongodb to fetch documents where date time difference between current server date and createdAt date is less 60 minutes.

Mongoldb -v 3.0.10 currentDate = new Date(); db.blog.find({'blogStatus':'OPEN'})

want to apply something like this:

if currentDate.getMinutes() > 60 minutes true show document false don't show document

Nilesh K
  • 124
  • 8
  • this is duplicate. Just go with $gte or $lte (grater/lesser than) paremeter in query. – kWeglinski Sep 18 '16 at 20:18
  • Possible duplicate of [MongoDB/Mongoose querying at a specific date?](http://stackoverflow.com/questions/11973304/mongodb-mongoose-querying-at-a-specific-date) – kWeglinski Sep 18 '16 at 20:19

2 Answers2

2

If you want to get posts that are newer than 60 minutes old, then you need to include something like this in your query:

db.blog.find({
  blogStatus: 'OPEN',
  createdAt: {
    $gt: date,
  }
});

where date is a date calculated by subtracting 60 minutes from the current time. If you use something like Moment then you can use this to subtract minutes:

moment().subtract(60, 'minutes');

Make sure you get the format and timezone right for Mongo. This should work:

var date = moment().subtract(60, 'minutes').utc().format();

Without Moment and inside the Mongo shell, such a date can be constructed with something like:

var date = new Date(new Date() - 60 * 60 * 1000);
rsp
  • 107,747
  • 29
  • 201
  • 177
0

I finally used below query db.blog.find({'blogStatus':'OPEN','createdAt':{'$gte':date}})

Nilesh K
  • 124
  • 8