Home > OS >  MongoDB Aggregation Pipeline: $lt & $toDate
MongoDB Aggregation Pipeline: $lt & $toDate

Time:07-20

Given the following dataset (created using mongosh.exe):

use test
db.dates.insert({date: new Date('2022-01-01')})

When trying to query this data using MongoDB's aggregation pipeline, I'm finding that the date is not returned when using the following query:

db.dates.aggregate([{ $match: { date: { $lt: { $toDate: "2023-01-01" } } } }]);

Does anyone have any ideas (I need to do this with an operator rather than something like the ISODate function)?

CodePudding user response:

You'll need to use an $expr (aggregation expression) within your $match stage

db.dates.aggregate([
  { $match: { $expr: { $lt: ["$date", { $toDate: "2023-01-01" }] } } },
]);

https://www.mongodb.com/docs/manual/reference/operator/query/expr/

  • Related