Querying Documents
Learn about different query operators ($eq, $gt, $lt, $in, etc.) and how to construct complex queries to retrieve specific documents.
MongoDB Array Operators: $all, $elemMatch, $size
Introduction
MongoDB provides powerful array operators that allow you to query and manipulate data stored in array fields. This document explores three essential array operators: $all
, $elemMatch
, and $size
.
$all Operator
The $all
operator selects documents where the specified array field contains all the elements specified in the query. The order of elements in the array does not matter.
Example
Consider a collection named products
with documents like this:
{
"_id": ObjectId("654321abc123def456ghi789"),
"name": "Laptop",
"tags": ["electronics", "computer", "portable"]
}
{
"_id": ObjectId("987654xyz321fed098uvw654"),
"name": "Smartphone",
"tags": ["electronics", "mobile", "camera"]
}
{
"_id": ObjectId("123456def654abc987zyx321"),
"name": "Book",
"tags": ["literature", "novel", "paperback"]
}
To find all products that have both "electronics" and "computer" tags, you can use the following query:
db.products.find({
tags: { $all: ["electronics", "computer"] }
})
$elemMatch Operator
The $elemMatch
operator selects documents where at least one element in the array field matches all the specified query criteria.
Example
Consider a collection named students
with documents like this:
{
"_id": ObjectId("654321abc123def456ghi789"),
"name": "Alice",
"grades": [
{ "subject": "Math", "score": 90 },
{ "subject": "Science", "score": 85 }
]
}
{
"_id": ObjectId("987654xyz321fed098uvw654"),
"name": "Bob",
"grades": [
{ "subject": "Math", "score": 70 },
{ "subject": "Science", "score": 95 }
]
}
To find students who have at least one grade where the subject is "Math" and the score is greater than 80, you can use the following query:
db.students.find({
grades: { $elemMatch: { subject: "Math", score: { $gt: 80 } } }
})
$size Operator
The $size
operator selects documents where the specified array field is a certain size (number of elements).
Example
Using the products
collection from the $all
example:
{
"_id": ObjectId("654321abc123def456ghi789"),
"name": "Laptop",
"tags": ["electronics", "computer", "portable"]
}
{
"_id": ObjectId("987654xyz321fed098uvw654"),
"name": "Smartphone",
"tags": ["electronics", "mobile", "camera"]
}
{
"_id": ObjectId("123456def654abc987zyx321"),
"name": "Book",
"tags": ["literature", "novel", "paperback"]
}
To find all products that have exactly 3 tags, you can use the following query:
db.products.find({
tags: { $size: 3 }
})
To find all products that have exactly 2 tags, the result set would be empty.