Filter query on array of embedded document with MongoDB?

MongoDBDatabaseBig Data Analytics

For this, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo736.insertOne(
...    {
...       "_id": "101",
...       "details1": [
...          {
...             "details2": [
...                {
...                   "details3": {
...                      "Name": "John"
...                   }
...                }
...             ]
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo736.insertOne(
...    {
...       "_id": "102",
...       "details1": [
...          {
...             "details2": [
...                {
...                   "details3": {
...                      "Name": "Robert"
...                   }
...                }
...             ]
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : "102" }

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

> db.demo736.find();

This will produce the following output −

{ "_id" : "101", "details1" : [ { "details2" : [ { "details3" : { "Name" : "John" } } ] } ] }
{ "_id" : "102", "details1" : [ { "details2" : [ { "details3" : { "Name" : "Robert" } } ] } ] }

Following is the query to filter array of embedded documents (3 levels) in MongoDB −

> db.demo736.aggregate([
...    {
...       "$unwind": "$details1"
...    },
...    {
...       "$unwind": "$details1.details2"
...    },
...    {
...       "$match": {
...          "details1.details2.details3.Name": "Robert"
...       }
...    },
...    {
...    $project: {
...       _id: 0,
...       Name: "$details1.details2.details3",
...    }
... }
... ])

This will produce the following output −

{ "Name" : { "Name" : "Robert" } }
raja
Published on 30-Jun-2020 11:17:24
Advertisements