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
Retrieve only the queried element in an object array in MongoDB collection?
To retrieve only the matching element from an object array in MongoDB, use the $elemMatch projection operator or the $ positional projection operator. Both return only the first array element that matches the query condition.
Create Sample Data
db.objectArray.insertMany([
{
"Persons": [
{"PersonName": "Adam", "PersonSalary": 25000},
{"PersonName": "Larry", "PersonSalary": 27000}
]
},
{
"Persons": [
{"PersonName": "David", "PersonSalary": 32000},
{"PersonName": "Carol", "PersonSalary": 77000}
]
}
]);
Method 1: Using $elemMatch
$elemMatch in the projection filters the array to return only the matching element ?
db.objectArray.find(
{"Persons.PersonSalary": 25000},
{_id: 0, Persons: {$elemMatch: {"PersonSalary": 25000}}}
).pretty();
{
"Persons": [
{
"PersonName": "Adam",
"PersonSalary": 25000
}
]
}
_id: 0 excludes the _id field. $elemMatch returns only the first array element where PersonSalary equals 25000.
Method 2: Using $ Positional Operator
The $ operator projects the first matching array element ?
db.objectArray.find(
{"Persons.PersonSalary": 25000},
{_id: 0, "Persons.$": 1}
).pretty();
{
"Persons": [
{
"PersonName": "Adam",
"PersonSalary": 25000
}
]
}
Comparison
| Operator | Syntax | Returns |
|---|---|---|
$elemMatch |
{array: {$elemMatch: {condition}}} |
First matching element; can use complex conditions |
$ |
{"array.$": 1} |
First matching element from query condition |
Conclusion
Use $elemMatch projection for complex filtering conditions on array elements. Use the $ positional operator for simpler cases where the query condition already matches the desired element. Both return only the first matching array element, not the entire array.
