skip to Main Content

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


  1. Chosen as BEST ANSWER

    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
        }
      }
    ]
    

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

    new Date("2023-01-24T00:00:00+00:00")
    
    Login or Signup to reply.
  3. 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"}]}
                    ]
                }
            }
        }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search