Split a document by its subdocuments in MongoDB


To split a document by its subdocuments, use $unwind in MongoDB. 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();

This will produce the following output −

{
   "_id" : ObjectId("5e48f953dd099650a5401a51"),
   "Name" : "Chris",
   "Subjects" : [
      "MySQL",
      "MongoDB"
   ]
}

Following is the query to split a document by its subdocuments −

> db.demo276.aggregate( [ { $unwind : "$Subjects" } ] )

This will produce the following output −

{ "_id" : ObjectId("5e48f953dd099650a5401a51"), "Name" : "Chris", "Subjects" : "MySQL" }
{ "_id" : ObjectId("5e48f953dd099650a5401a51"), "Name" : "Chris", "Subjects" : "MongoDB" }

Updated on: 31-Mar-2020

490 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements