How to retrieve Students with a Specific Date in a Collection

{
  "branchId": "NLR001",
  "monthYear": [
    {
      "dateMonthYear": "1-01-2023",
      "standardId": [
        {
          "standardId": "UKG",
          "stAttendanceStatus": [
            {
              "stRollNo": "RoleNumber-000",
              "attendanceStatus": "true"
            }
          ]
        }
      ]
    }
  ]
}

above is my collection

Question: Find all students with "dateMonthYear": "1-01-2023"

I added $match as below: I am getting other Dates lists also "2-01-2023" and "2-01-2023" etc…

How to find only collects with "monthYear.dateMonthYear": "1-01-2023"

{ "branchId": "NLR001" },
    { "monthYear.dateMonthYear": "1-01-2023" }

Hi @Mohammed_Ali4 and welcome to MongoDB community forums!!

I tried to replicate the above json into my local environment and tried to execute the aggregation pipeline stage as:

Atlas atlas-b8d6l3-shard-0 [primary] test> db.post233547.aggregate([ {
...   $match: {
...       "branchId": "NLR001",
...       "monthYear.dateMonthYear": {
...         $eq: ISODate("2022-12-31T18:30:00.000+00:00")
...       }
...     }
... }])
[
  {
    _id: ObjectId("64a6654cfb77c7c470e09843"),
    branchId: 'NLR001',
    monthYear: [
      {
        dateMonthYear: ISODate("2022-12-31T18:30:00.000Z"),
        standardId: [ { standardId: 'UKG', stAttendanceStatus: [ [Object] ] } ]
      }
    ]
  }
]

However, I would like to suggest a more efficient schema design to optimize the querying process and avoid potential limitations.
I would suggest you reconsider the schema design to something like this:

{
  "branchId": "NLR001",
  "dateMonthYear": "1-01-2023",
  "standardId": "UKG",
  "attendanceData": [
    {
      "stRollNo": "RoleNumber-000",
      "attendanceStatus": true
    }
  ]
}

which would make the query more proficient and easy.

Please reach out if you have any further questions.

Regards
Aasawari

1 Like