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
Extract subarray value in MongoDB?
To extract a subarray value in MongoDB, you can use the $elemMatch projection operator to return only the first array element that matches the specified condition.
Syntax
db.collection.find(
{ query },
{ arrayField: { $elemMatch: { field: "value" } } }
);
Sample Data
Let us first create a collection with documents ?
db.extractSubArrayDemo.insertOne({
_id: 101,
"clientName": "Larry",
"ClientDetails": [
{
"ClientProjectName": "Online Game",
"DeveloperTeamSize": 10
},
{
"ClientProjectName": "Pig Dice Game",
"DeveloperTeamSize": 12
},
{
"ClientProjectName": "Web Student Tracker",
"DeveloperTeamSize": 11
}
]
});
{ "acknowledged": true, "insertedId": 101 }
Display all documents from the collection ?
db.extractSubArrayDemo.find().pretty();
{
"_id": 101,
"clientName": "Larry",
"ClientDetails": [
{
"ClientProjectName": "Online Game",
"DeveloperTeamSize": 10
},
{
"ClientProjectName": "Pig Dice Game",
"DeveloperTeamSize": 12
},
{
"ClientProjectName": "Web Student Tracker",
"DeveloperTeamSize": 11
}
]
}
Example: Extract Specific Array Element
Extract only the "Pig Dice Game" project details from the ClientDetails array ?
db.extractSubArrayDemo.find(
{ '_id': 101 },
{
_id: 0,
ClientDetails: { $elemMatch: { ClientProjectName: 'Pig Dice Game' } }
}
).pretty();
{
"ClientDetails": [
{
"ClientProjectName": "Pig Dice Game",
"DeveloperTeamSize": 12
}
]
}
Key Points
-
$elemMatchreturns only the first matching array element. - The result still wraps the matched element in an array format.
- Use
_id: 0to exclude the document ID from results.
Conclusion
The $elemMatch projection operator effectively extracts specific subarray elements based on field conditions. It's particularly useful when you need only one matching element from large arrays instead of the entire array.
Advertisements
