How to unwind array inside object in mongodb?

by hal.littel , in category: MySQL , a month ago

How to unwind array inside object in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , a month ago

@hal.littel 

To unwind an array inside an object in MongoDB, you can use the $unwind operator in an aggregation pipeline. Here's an example of how you can do this:


Let's say you have a collection called "students" with documents structured like this:


{ _id: 1, name: "Alice", grades: [ {subject: "Math", score: 90}, {subject: "History", score: 85} ] }


To unwind the "grades" array inside each document in the "students" collection, you can use the following aggregation pipeline:


db.students.aggregate([ { $unwind: "$grades" } ])


This will result in multiple documents where each document will represent one of the items in the "grades" array, while preserving the other fields from the original document.


You can further manipulate the data by adding additional stages to your aggregation pipeline after the $unwind stage, such as $group, $match, $project, etc.