Check out the solution in the video MongoDB: Extracting An Array With Unwind. In development, we frequently work with arrays and in some cases, we want to extract all items from an array. In MongoDB, we can extract all items from an array by using the unwind function. This allows us to do various things with these items, such as storing them in their own document if we prefer. Or we can add these items to other documents by extracting them.
Some things to consider:
- I use the pretty command to make the output look clear
- We have to use the project call
- We add new items to new documents
Check out the highest-rated Automating ETL course on Udemy, if you're interested in data.
We'll notice how easy it is to add new items to these new documents when we unwind the array. In the project, we are selecting the fields that we want selected - without doing this, we wouldn't return anything. Keep this in mind when using the project command as well.