Search code examples
node.jsmongodbmongoosedate-range

How can I query mongoDB based on date range using node?


I recognize there are many questions like this already, but all of the answers I have seen don't apply to my situation. So please bear with me.

I have this query right now that works:

let query = [
        {
            $match: { 
              'cityState': cityState,
              'userId': userId
            }
        }];

This is how the query is run:

Review.aggregate(query,function(err,response){

I'm new to web so I don't quite know what tooling I'm using above. I'd like to adjust the query above to take two dates as inputs, and return Reviews that match all of the params. The Review object has a givenDate field that I'd like to compare against. So the query should return all reviews that have a givenDate between the two dates I specify, and that match the cityState and userId.

What do I need to do to the query to make this work? The dates I am passing in are in the following format: 2019-08-21T07:04:48.263Z


Solution

  • To compare, both the values of the database and the supplied inputs must be of same data type. In this case, convert the string inputs to date objects, and use them in the query against a range of dates in the database

    let inputDateFrom = new Date(inputDate1) // inputDate1 is a string
    let inputDateTo = new Date(inputDate2)
    
    let query = [
      {
          $match: { 
              'givenDate': { $gte: inputDateFrom, $lte: inputDateTo },
              'cityState': cityState,
              'userId': userId
          }
      }
    ];
    


    Here is an example of querying a date field with a range of dates: Query for Ranges.