Using $All and $ElemMatch in MongoDB
$all
The $all
operator is used with arrays. Let's say you have an array field called interests
. If you want to find documents where the interests
include "Travelling", you can easily do that:
// array field
"interests" : [ "Travelling", "Gaming", "Reading" ]
db.students.find({ interests: "Travelling" }) // 'students' is the name of the collection.
However, if you are asked to find documents where the interests
include both "Travelling" and "Reading", how would you do that?
db.students.find({ interests: ["Travelling", "Reading"] });
If you run this query, it will throw an error because this query looks for an exact match of the array ["Travelling", "Reading"]
. To find documents that include both "Travelling" and "Reading" regardless of their positions in the array, you need the $all
operator:
db.students.find({ interests: { $all: ["Travelling", "Reading"] } });
- With
$all
, the positions of the elements in the array do not matter. As long as the specified elements are present in the array, the document will be retrieved.
$elemMatch
The $elemMatch
operator is used for matching elements in an array of objects.
Example:
Suppose your students
collection has documents with a grades
array field, where each element is an object representing a subject and a score:
{
"name": "Alice",
"grades": [
{ "subject": "Math", "score": 90 },
{ "subject": "English", "score": 85 }
]
},
{
"name": "Bob",
"grades": [
{ "subject": "Math", "score": 75 },
{ "subject": "English", "score": 95 }
]
},
{
"name": "Charlie",
"grades": [
{ "subject": "Math", "score": 90 },
{ "subject": "English", "score": 90 }
]
}
If you want to find students who scored more than 80 in Math, you can use the $elemMatch
operator:
db.students.find({
grades: { $elemMatch: { subject: "Math", score: { $gt: 80 } } }
});
This query will return the documents for Alice and Charlie, but not for Bob because his Math score is not greater than 80.
Conclusion:
-
$all
is used to match elements in an array. -
$elemMatch
is used to match elements in an array of objects, where each element needs to satisfy multiple conditions.
Top comments (0)