I have an aggregation pipeline like this in MongoDB:
[
{
"$match": {
"event": "LOG_ACCESS",
"createdAt": {
"$gte": ISODate("2023-01-24T00:00:00+00:00"),
"$lt": ISODate("2023-01-25T00:00:00+00:00")
}
}
}
]
That works, but I wonder if I can reformulate it using pure JSON syntax (note that ISODate()
doesn’t conform with JSON syntax). I have checked the MongoDB extended JSON and the $date
operator looks nice, so I tryed:
[
{
"$match": {
"event": "LOG_ACCESS",
"createdAt": {
"$gte": {"$date": "2023-01-24T00:00:00+00:00"},
"$lt": {"$date": "2023-01-25T00:00:00+00:00"}
}
}
}
]
but it doesn’t work. I get this error:
Field must not begin with ‘$’ or ‘.’, field path was: $date
Is there any way of expressing the above query in pure JSON?
Thanks in advance for your feedback!
3
Answers
For the records (and although I prefer this solution) this also works (but requires two stages):
ISODate
is an alias in the mongo shell fornew Date()
, tryAs far as I know
$date
is not used for querying/aggregations, but you should be able to use$toDate
. It’s important to note that you also need to wrap the conversion to a date in an expression.Example: