Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Split a document by its subdocuments in MongoDB
To split a document by its subdocuments, use $unwind in MongoDB. This operator deconstructs an array field from the input documents to output a document for each element.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayFieldName" }
]);
Sample Data
Let us create a collection with documents ?
db.demo276.insertOne({
"Name": "Chris",
"Subjects": ["MySQL", "MongoDB"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e48f953dd099650a5401a51")
}
Display all documents from a collection with the help of find() method ?
db.demo276.find().pretty();
{
"_id": ObjectId("5e48f953dd099650a5401a51"),
"Name": "Chris",
"Subjects": [
"MySQL",
"MongoDB"
]
}
Example: Split Document by Subdocuments
Following is the query to split a document by its subdocuments ?
db.demo276.aggregate([
{ $unwind: "$Subjects" }
]);
{ "_id": ObjectId("5e48f953dd099650a5401a51"), "Name": "Chris", "Subjects": "MySQL" }
{ "_id": ObjectId("5e48f953dd099650a5401a51"), "Name": "Chris", "Subjects": "MongoDB" }
How It Works
The $unwind operator creates separate documents for each array element. The original document with ["MySQL", "MongoDB"] becomes two documents: one with "MySQL" and another with "MongoDB".
Conclusion
Use $unwind in an aggregation pipeline to split documents containing arrays into multiple documents. Each array element becomes a separate document with the same _id and other fields.
