Home > front end >  Avoid ISODate() in MongoDB aggregation framework so pipeline can be pure JSON
Avoid ISODate() in MongoDB aggregation framework so pipeline can be pure JSON

Time:01-27

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!

CodePudding user response:

As 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:

[
    {
        "$match": {
            "event": "LOG_ACCESS",
            "$expr": {
                "$and": [
                    {"$gte": ["$createdAt", {"$toDate": "2023-01-24T00:00:00 00:00"}]},
                    {"$lte": ["$createdAt", {"$toDate": "2023-01-25T00:00:00 00:00"}]}
                ]
            }
        }
    }
]

CodePudding user response:

ISODate is an alias in the mongo shell for new Date(), try

new Date("2023-01-24T00:00:00 00:00")

CodePudding user response:

For the records (and although I prefer this solution) this also works (but requires two stages):

[
  {
    "$addFields": {
      "year": { "$year": "$createdAt" },
      "month": { "$month": "$createdAt" },
      "day": { "$dayOfMonth": "$createdAt" }
    }
  },
  {
    "$match": {
      "event": "LOG_ACCESS"
      "month": 1,
      "year": 2023,
      "day": 24
    }
  }
]
  • Related