Filter sub documents by sub document in MongoDB?


For this, use aggregate() along with $unwind. Let us create a collection with documents −

> db.demo583.insert([
...    {
...       "details1" : [
...          {
...             "details2" : [
...                {
...                   "isMarried" : true,
...                   "Name" : "Chris"
...                },
...                {
...                   "isMarried" : true,
...                   "Name" : "Bob"
...                }
...             ]
...          },
...          {
...             "details2" : [
...                {
...                   "isMarried" : false,
...                   "Name" : "Chris"
...                },
...                {
...                   "isMarried" : true,
...                   "Name" : "Mike"
...                }
...             ]
...          }
...       ]
...    }
... ]);
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 1,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})

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

> db.demo583.find();

This will produce the following output −

{ "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : [
   { "details2" : [
      { "isMarried" : true, "Name" : "Chris" },
      { "isMarried" : true, "Name" : "Bob" }
   ] },
   { "details2" : [
      { "isMarried" : false, "Name" : "Chris" },
      { "isMarried" : true, "Name" : "Mike" }
   ] }
] }

Following is the query to filter sub documents by sub-document −

> var q= [
...    {
...       "$match": {
...          "details1.details2.isMarried": true,
...          "details1.details2.Name": "Chris"
...       }
...    },
...    {
...       "$unwind": "$details1"
...    },
...    {
...       "$unwind": "$details1.details2"
...    },
...    {
...       "$match": {
...          "details1.details2.isMarried": true,
...          "details1.details2.Name": "Chris"
...       }
...    }
... ];
> db.demo583.aggregate(q).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"),
   "details1" : {
      "details2" : {
         "isMarried" : true,
         "Name" : "Chris"
      }
   }
}

Updated on: 15-May-2020

485 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements