Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Range Mongo Query using Meteor Js

Tags:

mongodb

meteor

I have an attribute in my collection called dateacquired and the date is formatted like: 2014-03-28 06:08:00.

I am needing to pull back all documents in my collection that are less than or equal to a month ago from the current date. I am just not sure how to write this query.

Anyone know how to start one something like this?

like image 479
dennismonsewicz Avatar asked Apr 15 '14 01:04

dennismonsewicz


1 Answers

I assume those dates are stored as strings? You can compare strings with the mongoDB comparison operators $gt or $lt and they work as you’d expect. I’m going to also use Sugar to make my life easier (highly recommended; add via mrt add sugarjs) which gives me the Date.create and Date.format methods which reduce this into a one-liner:

  var cursorOfDocumentsSinceOneMonthAgo = yourCollection.find({
    dateacquired:
      { $gt: Date.create("1 month ago").format("{yyyy}-{MM}-{dd} {hh}:{mm}:{ss}")
      }
    });
like image 67
Geoffrey Booth Avatar answered Oct 04 '22 22:10

Geoffrey Booth