How to unwind array inside object in mongodb?

by hal.littel , in category: MySQL , 4 months ago

How to unwind array inside object in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 4 months 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.

Related Threads:

How to update array inside object in mongodb?
How to properly unwind my array in mongodb?
How to find object inside object in mongodb?
How to get object values inside array in laravel?
How to push to an array inside of a json object in a jsonb column in postgresql?
How to unwind data in MongoDB using PHP?