Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
I can print out each element of an array by iterating through all values, but can't get a specific element in MongoDB
In MongoDB, you can fetch specific elements from arrays using projection operators like $elemMatch or array indexing, which is more efficient than iterating through all values with forEach().
Syntax
// Using array index
db.collection.find({}, {"arrayField.index": 1});
// Using $elemMatch
db.collection.find({}, {arrayField: {$elemMatch: {field: "value"}}});
Sample Data
db.demo742.insertOne({
"userDetails": [
{
"userName": "Robert",
"CountryName": "UK"
},
{
"userName": "David",
"CountryName": "AUS"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ead790b57bb72a10bcf0677")
}
Method 1: Using Array Index (Get First Element)
db.demo742.find({}, {"userDetails.0": 1});
{
"_id": ObjectId("5ead790b57bb72a10bcf0677"),
"userDetails": [
{
"userName": "Robert",
"CountryName": "UK"
}
]
}
Method 2: Using $elemMatch (Get Specific Element)
db.demo742.find({}, {userDetails: {$elemMatch: {CountryName: "AUS"}}});
{
"_id": ObjectId("5ead790b57bb72a10bcf0677"),
"userDetails": [
{
"userName": "David",
"CountryName": "AUS"
}
]
}
Method 3: Using forEach() (Original Approach)
var ListOfCountryName = {};
db.demo742.find({}).forEach(function(doc) {
doc.userDetails.forEach(function(d) {
ListOfCountryName[d.CountryName] = d.CountryName;
});
});
printjson(ListOfCountryName);
{
"UK": "UK",
"AUS": "AUS"
}
Key Points
- Array indexing is fastest for getting elements by position.
- $elemMatch is ideal for filtering specific array elements by field values.
- forEach() provides full control but is slower for large datasets.
Conclusion
Use array indexing or $elemMatch projection operators to fetch specific array elements efficiently in MongoDB. These methods are more performant than iterating through all values with forEach().
Advertisements
