MongoDB query to get only specific fields in nested array documents?


To get only specific fields in nested array documents, use $filter along with $project. Let us create a collection with documents −

> db.demo342.insertOne({
...    "Id": "101",
...       "details1" : {
...          "details2" : [
...             {
...                "details3" : [
...                   {
...                      "Name": "Mike",
...                      "CountryName" : "US"
...                   },
...                   {
...                      "Name": "David",
...                      "CountryName" : "AUS"
...                   },
...                   {
...                      "Name": "Bob",
...                      "CountryName" : "UK"
...                   }
...                ]
...             }
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e53ef99f8647eb59e5620a9")
}

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

> db.demo342.find();

This will produce the following output −

{ "_id" : ObjectId("5e53ef99f8647eb59e5620a9"), "Id" : "101", "details1" : { "details2" : [ { "details3" : [ { "Name" : "Mike", "CountryName" : "US" }, { "Name" : "David", "CountryName" : "AUS" }, { "Name" : "Bob", "CountryName" : "UK" } ] } ] } }

Following is the query to get only specific fields in nested array documents −

> db.demo342.aggregate([
...    { "$project": {
...       "details1": {
...          "details2": {
...             "$filter": {
...                "input": {
...                   "$map": {
...                      "input": "$details1.details2",
...                      "in": {
...                         "details3": {
...                            "$filter": {
...                               "input": "$$this.details3",
...                               "cond": { "$eq": ["$$this.Name", "Bob"] }
...                            }
...                         }
...                      }
...                   }
...                },
...                "cond": { "$ne": ["$$this.details3", []] }
...             }
...          }
...       }
...    }}
... ])

This will produce the following output −

{ "_id" : ObjectId("5e53ef99f8647eb59e5620a9"), "details1" : { "details2" : [ { "details3" : [ { "Name" : "Bob", "CountryName" : "UK" } ] } ] } }

Updated on: 02-Apr-2020

660 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements