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
How to get the matching document inside an array in MongoDB?
To get the matching document inside an array in MongoDB, use the $elemMatch operator. This operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
Syntax
db.collection.find({
"arrayField": {
$elemMatch: {
"field1": "value1",
"field2": "value2"
}
}
});
Sample Data
db.getMatchingDocumentDemo.insertMany([
{
_id: 1,
"UserDetails": [
{
"UserName": "John",
"UserAge": 23
}
]
},
{
_id: 2,
"UserDetails": [
{
"UserName": "Larry",
"UserAge": 24
}
]
}
]);
{
"acknowledged": true,
"insertedIds": {
"0": 1,
"1": 2
}
}
Display all documents to verify the data ?
db.getMatchingDocumentDemo.find().pretty();
{
"_id": 1,
"UserDetails": [
{
"UserName": "John",
"UserAge": 23
}
]
}
{
"_id": 2,
"UserDetails": [
{
"UserName": "Larry",
"UserAge": 24
}
]
}
Example: Find Document with Matching Array Element
Find documents where UserDetails array contains an element with UserAge equal to 24 ?
db.getMatchingDocumentDemo.find({
UserDetails: {
$elemMatch: {
UserAge: 24
}
}
});
{
"_id": 2,
"UserDetails": [
{
"UserName": "Larry",
"UserAge": 24
}
]
}
Key Points
-
$elemMatchreturns the entire document when at least one array element matches all criteria. - Use
$elemMatchwhen you need to match multiple conditions within the same array element. - Without
$elemMatch, MongoDB would match conditions across different array elements.
Conclusion
The $elemMatch operator effectively finds documents containing array elements that match specific criteria. It ensures all conditions are satisfied by the same array element, making it essential for precise array queries.
Advertisements
