Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }Advertisements