Morton
Morton

Reputation: 5760

How to use $gte and $lte between date with `$filter`

I have a code query $gte date, it works fine.

cityCollection.aggregate([
    { 
      "$project": { 
          theater: true,
          movie: {
            $filter: {
              input: {
                $map: {
                  input: "$movie",
                  as: "movie",
                  in: {
                      cnName: "$$movie.cnName",
                      enName: "$$movie.enName",
                      releasedTime: {
                        $filter: {
                          input: "$$movie.releasedTime",
                          as: "movie",
                          cond: { $and:{
                            $gte: [ "$$movie", new Date(`${today} 20:00:00.000Z`) ]
                          }}
                        }
                      }
                  }
                }
              },
              as: "movie",
              cond: "$$movie"
            }
          }
      }
    }
])
    .then(drivers => res.send(drivers))
    .catch(next);

Now i want to query between two date, i try to add $lte inside my code like this:

releasedTime: {
   $filter: {
      input: "$$movie.releasedTime",
      as: "movie",
      cond: {
        $gte: [ "$$movie", new Date(`${today} 20:00:00.000Z`) ],
        $lte: [ "$$movie", new Date(`${today} 22:00:00.000Z`) ] 
      }
   }
}

But i get the error:

{
    "error": "An object representing an expression must have exactly one field: { $gte: [ \"$$movie\", new Date(1526328000000) ], $lte: [ \"$$movie\", new Date(1526335200000) ] }"
}

I looking for some solution find $and,so i try to add $and in my code like this:

releasedTime: {
  $filter: {
    input: "$$movie.releasedTime",
    as: "movie",
    cond: { $and:{
      $gte: [ "$$movie", new Date(`${today} 20:00:00.000Z`) ],
      $lte: [ "$$movie", new Date(`${today} 22:00:00.000Z`) ] 
    }}
  }
}

It still shows the same error, i have no idea what step should i try.

Any help would be appreciated. Thanks in advance.

Upvotes: 1

Views: 5623

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151122

It's brackets [] and not braces {}, mostly because it's an "array of conditions" in the context of aggregation usage.

releasedTime: {
  $filter: {
    input: "$$movie.releasedTime",
    as: "movie",
    cond: { $and:[
      { $gte: [ "$$movie", new Date(`${today} 20:00:00.000Z`) ] },
      { $lt: [ "$$movie", new Date(`${today} 22:00:00.000Z`) ] }
    ]}
  }
}

There are actually examples at $and (aggregation) within the documentation. Such as right here

Also note you typically mean $lt when you want "up to" a specific range amount. Always go "less than" the "next highest value", rather than inclusive of the "largest possible".

Upvotes: 5

Related Questions