I can print out each element of an array by iterating through all values, but can't get a specific element in MongoDB


To fetch a specific element, iterate with forEach(). Let us create a collection with documents −

> db.demo742.insertOne({ "userDetails": [ { "userName":"Robert", "CountryName":"UK" }, { "userName":"David", "CountryName":"AUS" } ]} );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead790b57bb72a10bcf0677")
}

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

> db.demo742.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5ead790b57bb72a10bcf0677"),
   "userDetails" : [
      {
         "userName" : "Robert",
         "CountryName" : "UK"
      },
      {
         "userName" : "David",
         "CountryName" : "AUS"
      }
   ]
}

Following is the query to get element from an array −

> var ListOfCountryName= {};
> db.demo742.find({}).forEach(function(doc) {
...    doc.userDetails.forEach(function (d){
...       ListOfCountryName[d.CountryName] =d.CountryName;
...    });
... }
... )
> printjson(ListOfCountryName);

This will produce the following output −

{ "UK" : "UK", "AUS" : "AUS" }

Updated on: 30-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements