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
MongoDB query to match documents that contain an array field
To match documents that contain an array field, use the $elemMatch operator. This operator matches documents where at least one array element meets all specified criteria within a single element.
Syntax
db.collection.find({
"arrayField": {
"$elemMatch": {
"field1": "value1",
"field2": "value2"
}
}
});
Sample Data
Let us create a collection with documents ?
db.demo592.insertMany([
{
"id": 101,
"details": [
{ "Name": "Chris", "Value": "200" },
{ "Name": "David", "Value": "800" }
]
},
{
"id": 102,
"details": [
{ "Name": "Chris", "Value": "500" },
{ "Name": "David", "Value": "900" }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e930d8ffd2d90c177b5bcd6"),
ObjectId("5e930d90fd2d90c177b5bcd7")
]
}
Display All Documents
db.demo592.find();
{ "_id": ObjectId("5e930d8ffd2d90c177b5bcd6"), "id": 101, "details": [
{ "Name": "Chris", "Value": "200" },
{ "Name": "David", "Value": "800" }
] }
{ "_id": ObjectId("5e930d90fd2d90c177b5bcd7"), "id": 102, "details": [
{ "Name": "Chris", "Value": "500" },
{ "Name": "David", "Value": "900" }
] }
Example: Complex Array Matching
Find documents where both Chris has Value >= 500 AND David has Value >= 600 ?
db.demo592.find({
"$and": [
{ "details": { "$elemMatch": { "Name": "Chris", "Value": { "$gte": "500" } } } },
{ "details": { "$elemMatch": { "Name": "David", "Value": { "$gte": "600" } } } }
]
});
{ "_id": ObjectId("5e930d90fd2d90c177b5bcd7"), "id": 102, "details": [
{ "Name": "Chris", "Value": "500" },
{ "Name": "David", "Value": "900" }
] }
Key Points
-
$elemMatchensures all conditions are met within a single array element - Use
$andto match multiple array elements with different criteria - Without
$elemMatch, conditions might match across different array elements
Conclusion
The $elemMatch operator is essential for querying arrays in MongoDB. It ensures that all specified conditions are satisfied by the same array element, providing precise matching for complex array queries.
Advertisements
