DEV Community

Cover image for $All and $ElemMatch in MongoDB
KAWSAR KABIR
KAWSAR KABIR

Posted on

$All and $ElemMatch in MongoDB

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.
Enter fullscreen mode Exit fullscreen mode

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"] });
Enter fullscreen mode Exit fullscreen mode

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"] } });
Enter fullscreen mode Exit fullscreen mode
  • 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 }
  ]
}
Enter fullscreen mode Exit fullscreen mode

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 } } }
});
Enter fullscreen mode Exit fullscreen mode

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)