I am new to mongodb so I hope this does not come-off as a very basic question. I've tried to apply what I've found but somehow I am missing some part and need help:
I have two parent-child collections in the following format:
Collection Name : members (Parent Records)
{
{
recordNo: 101, //member id
registerdDate: '01-Jan-2024',
personName : "James"
},
{
recordNo: 102,
registerdDate: '05-Feb-2024',
personName : "Smith"
},
{
recordNo: 103,
registerdDate: '16-Aug-2023',
personName : "Alex"
}
}
Collection Name : memberActivities (Child Records)
{
{
recordNo: 101, //Reference to members.recordNo in above collection
activityDate: '05-Jan-2024',
activity:[ //Array
0:{ Comments: "Played Chess" }
1:{ Comments: "Played Hockey" }
2:{ Comments: "Played Cricket" }
]
},
{
recordNo: 101,
activityDate: '06-Jan-2024',
activity:[ //Array
0:{ Comments: "Outing with friends" }
]
},
{
recordNo: 102,
activityDate: '08-Feb-2024',
activity:[ //Array
0:{ Comments: "Played Basketball" }
]
},
{
recordNo: 103,
activityDate: '20-Sep-2023',
activity:[ //Array
0:{ Comments: "Played Cricket" }
]
}
}
How should I form the "Aggregation Query" in MongoDB to get following output:
- Get "count" of all the "members" who is registered between '01-Jan-2024' to '29-Feb-2024' and played "Cricket" atleast once.
- Get "count" of all the "members" who is registered between '01-Jan-2024' to '29-Feb-2024' and never played "Cricket".
I am executing script in MongoDB compass for my queries.
First of all, if you want to filter by dates, you should set those fields as date types, not strings. Examples.
Then you can use $lookup to join the two collections, and $match to filter within the array to include or exclude the activities.
Example include
Example exclude