Find in MongoDB documents with filled nested array and reshape the documents result


Let us first create a collection with documents −

> db.demo187.insertOne(
...    {
...      "_id" : "101",
...      "Details" : [
...         { "Subject" : "MongoDB" },
...         { "Subject" : "MySQL" }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo187.insertOne(
...   {
...      "_id" : "102",
...      "Details" : [
...         { }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : "102" }
> db.demo187.insertOne(
...   {
...      "_id" : "103",
...      "Details" : [
...         { "Subject" : "MongoDB" },
...         { "Subject" : "MySQL" }
...      ]
...   }
...);
{ "acknowledged" : true, "insertedId" : "103" }

Display all documents from a collection with the help of find() method −

> db.demo187.find();

This will produce the following output −

{ "_id" : "101", "Details" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] }
{ "_id" : "102", "Details" : [ {  } ] }
{ "_id" : "103", "Details" : [ { "Subject" : "MongoDB" }, { "Subject" : "MySQL" } ] }

Following is the query to find in MongoDB documents with filled nested array −

> db.demo187.aggregate([
...
...   {$unwind: '$Details'},
...
...   {$project: {Subject: '$Details.Subject'}},
...
...   {$match: {Subject: {$exists: true}}}
... ])

This will produce the following output −

{ "_id" : "101", "Subject" : "MongoDB" }
{ "_id" : "101", "Subject" : "MySQL" }
{ "_id" : "103", "Subject" : "MongoDB" }
{ "_id" : "103", "Subject" : "MySQL" }

Updated on: 27-Mar-2020

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements