Hello!

I have two collections: courses and progress. Course has some properties including an array of modules, each module having an array of lessons, each lesson having an id and a name. Progress has a unique combination of courseId and userId and also an array of lessons, each lesson having an id and a status.

I want to write an aggregation which returns a course by its id with an array of lessons enriched with a status (if we find a corresponding lesson with the same id in progress collection).

I wrote an aggregation with match, lookup, set and project stages, but in the resulting lessons array objects are merged into one for some reason.

Here is the playground with example data and my aggregation pipeline. Thanks in advance for any help!

Alright, so while my previous comment was on approval (I’m starting to get the gist here), I’ve come up with a working aggregation pipeline – here is the playground.

However, since I’m relatively new to MongoDB aggregations, it might be not as effective as it could’ve been, so I would be glad if anyone shared how to improve it. Thanks!

So, while the post was waiting to be approved, I’ve managed to make the aggregation work to some extent, now I have the result almost as needed, except that resulting modules is an object, but I need it to be an array.

This happens because of unwind and I’m not sure how to best handle it. Here’s the updated playground code.

1 Like

Thanks for sharing the solution.

Your OP is in my bookmark until I have time to really look at it.

1 Like

To get the result modules as an array rather than an object you could replace

"modules": 1

in your final $project with

"modules": [ "$modules" ]

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.