Get fields from multiple sub-documents that match a condition in MongoDB?


To get fields from multiple sub-documents, use MongoDB aggregate with $unwind. Let us create a collection with documents −

> db.demo671.insertOne(
... {
...
...    "details" : [
...    {
...       "id" : "1"
...    },
...    {
...       CountryName:"US",
...       "details1" : [
...       {
...       "id" : "1"
...       },
...       {
...          "id" : "2"
...       }
...       ]
...    },
... {
...    CountryName:"UK",
...    "details1" : [
...    {
...       "id" : "2"
...    },
...    {
...       "id" : "1"
...    }
...    ]
... },
... {
...    CountryName:"AUS",
...    "details1" : [
...       {
...          "id" : "1"
...       }
...       ]
...    }
... ]
... }
... )
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3e5d004263e90dac943e0")
}

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

> db.demo671.find();

This will produce the following output −

{ "_id" : ObjectId("5ea3e5d004263e90dac943e0"), "details" : [ { "id" : "1" }, { "CountryName" : "US", "details1" : [ { "id" : "1" }, { "id" : "2" } ] }, { "CountryName" : "UK", "details1" : [ { "id" : "2" }, { "id" : "1" } ] }, { "CountryName" : "AUS", "details1" : [ { "id" : "1" } ] } ] }

Here is the query to get fields from multiple sub-documents that match a condition in MongoDB −

> db.demo671.aggregate([
...
...   {$unwind: '$details'},
...
...   {$match: {'details.details1.id': '1'}},
...
...   {$project: {_id: 0, Country: '$details.CountryName'}}
... ]).pretty()

This will produce the following output −

{ "Country" : "US" }
{ "Country" : "UK" }
{ "Country" : "AUS" }

Updated on: 13-May-2020

545 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements