skip to Main Content

I have mongo collection with objects with 2 fields: available_from and available_to

Mongo collection:

[
  {
    "_id": ObjectId("66ed4d5ede0184e906f9397a"),
    "available_from": ISODate("2024-09-20T00:00:00.000Z"),
    "available_to": ISODate("2024-09-30T00:00:00.000Z")
  }
]

I want to get all dates which are in specific array

For example my input is: {$match: {"available_from": "2024-09-20", "available_to": "2024-09-30"}} but this input still does not show me anything.

There is mongo playground:

What should i change?

2

Answers


    • Your query missed the time component, causing an exact match failure.
    • Please include time range along with the date.
    • Updated query is as follows:
    db.collection.aggregate({
      $match: {
        "available_from": {
          $gte: ISODate("2024-09-20T00:00:00.000Z")
        },
        "available_to": {
          $lte: ISODate("2024-09-30T23:59:59.999Z")
        }
      }
    })
    
    Login or Signup to reply.
  1. Answer 1: The query in your question is:

    {
      $match: {
        available_from: "2024-09-20",
        available_to: "2024-09-30"
      }
    }
    

    The only fix needed for exact-match is to covert it to ISODate:

    {
      $match: {
        available_from: ISODate("2024-09-20"),
        available_to: ISODate("2024-09-30")
      }
    }
    

    Answer 1 Mongo Playground


    Answer 2: The query in your linked mongo playground is:

    {
      $match: {
        available_from: { $lte: "2025-09-20T00:00:00:00" },
        available_to: { $gte: "2024-09-30T00:00:00:00" }
      }
    }
    

    Notice that the time part has four pairs of 00 instead of three. The fixes needed are:

    1. remove the extra :00
    2. put a Z (for UTC)
    3. convert to ISODate
    {
      $match: {
        available_from: { $lte: ISODate("2025-09-20T00:00:00Z") },
        available_to: { $gte: ISODate("2024-09-30T00:00:00Z") }
      }
    }
    

    Answer 2 Mongo Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search