conflict between mongo find and aggregate results conflict between mongo find and aggregate results mongoose mongoose

conflict between mongo find and aggregate results


The query you have currently is comparing the stored dates with strings, you need to create date object representations from the strings in order for the query to work. Use the native JS Date() constructor to create a date instance:

var end = new Date("2016-08-27 23:59:59"),    start = new Date("2016-08-19");var pipeline = [    {        "$match": {            "restaurantId": 138,            "createdAt": { "$lte": end, "$gte": start }        }    },    {        "$group": {            "_id": null,            "count": { "$sum": 1 }        }    }]

For more details on dealing with dates in MongoDB, refer to the docs, but in a nutshell:

The mongo shell provides various methods to return the date, either as a string or as a Date object:

  • Date() method which returns the current date as a string.
  • new Date() constructor which returns a Date object using the ISODate() wrapper.
  • ISODate() constructor which returns a Date object using the ISODate() wrapper.

Internally, Date objects are stored as a 64 bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970), which results in a representable date range of about 290 millions years into the past and future.


If you are using the momentjs library, use the toDate() extension method to return the date objects:

var end = moment(Number(data.createdAt.to)).toDate(),    start =  moment(Number(data.createdAt.from)).toDate();

To append 23:59:59 to the date, you can use the startOf() and endOf() methods on the moment's date object, passing the string 'day' as arguments:

var start = moment(Number(data.createdAt.from)).startOf('day').toDate(); // set to 12:00 am for that datevar end = moment(Number(data.createdAt.to)).endOf('day').toDate(); // set to 23:59 pm for that date