Access Specific Element in MongoDB Array



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: 2020-06-30T07:59:03+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements