I've create a mongoplayground to make it easier to understand.
If I just change '$$date' to its date:
Even if I insert the variable inside date function:
Does anyone have any thoughts in why it doesn't work in compass and works in mongoplayground?
CodePudding user response:
For best practice, when comparing date string, it is required to convert as date
first (via $toDate
).
$lte: [ { $toDate: "$date" }, { $toDate: "$$date" }]
Comparison/Sort Order (MongoDB Manual) - String section
By default, MongoDB uses the simple binary comparison to compare strings.
Hence, comparing dates in string format will lead to an inaccurate result.