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 filter documents based on an array in MongoDB?
To filter documents based on an array in MongoDB, use the $elemMatch operator. The $elemMatch operator matches documents that contain an array field with at least one element that satisfies all the specified query criteria.
Syntax
db.collection.find(
{ arrayField: { $elemMatch: { field1: value1, field2: value2 } } }
);
Sample Data
Let us create a collection with documents ?
db.demo453.insertMany([
{ _id: 101, details: [ { Name: "David", Marks: 60 }, { Name: "Mike", Marks: 55} ] },
{ _id: 102, details: [ { Name: "Bob", Marks: 80 }, { Name: "Sam", Marks: 78} ] },
{ _id: 103, details: [ { Name: "Carol", Marks: 67 }, { Name: "John", Marks: 79} ] }
]);
{
"acknowledged": true,
"insertedIds": [101, 102, 103]
}
Display all documents from the collection ?
db.demo453.find();
{ "_id": 101, "details": [ { "Name": "David", "Marks": 60 }, { "Name": "Mike", "Marks": 55 } ] }
{ "_id": 102, "details": [ { "Name": "Bob", "Marks": 80 }, { "Name": "Sam", "Marks": 78 } ] }
{ "_id": 103, "details": [ { "Name": "Carol", "Marks": 67 }, { "Name": "John", "Marks": 79 } ] }
Example: Filter Documents with Array Elements
Find documents where at least one element in the details array has Marks greater than or equal to 75 ?
db.demo453.find(
{ details: { $elemMatch: {Marks: { $gte: 75 } } } }
);
{ "_id": 102, "details": [ { "Name": "Bob", "Marks": 80 }, { "Name": "Sam", "Marks": 78 } ] }
{ "_id": 103, "details": [ { "Name": "Carol", "Marks": 67 }, { "Name": "John", "Marks": 79 } ] }
Key Points
-
$elemMatchensures at least one array element matches all specified conditions. - Without
$elemMatch, MongoDB would match documents where different array elements satisfy different parts of the query. - Use
$elemMatchwhen querying arrays of embedded documents with multiple field conditions.
Conclusion
The $elemMatch operator is essential for filtering documents based on array content, ensuring that all query conditions are satisfied by the same array element, providing precise and reliable results.
Advertisements
