MongoDB $size
Operator
The $size
operator in MongoDB is used to query for documents where the size of a specified array field matches a specified value. It is commonly employed within the $match
stage of an aggregation pipeline to filter documents based on the size of an array. This guide will cover the syntax, examples, output, explanations, use cases, important points, and a summary of using the $size
operator in MongoDB aggregation.
Syntax
{ $match: { arrayField: { $size: sizeValue } } }
$match
: Aggregation stage to filter documents.arrayField
: The array field on which to apply the$size
operator.$size
: The operator that checks if the size of the array field is equal to the specified value.sizeValue
: The value to compare the size of the array against.
Example
Consider a collection named orders
with documents containing an items
array field. We want to find orders where the number of items in the array is 3.
db.orders.aggregate([
{
$match: {
"items": { $size: 3 }
}
}
]);
Output
The output will display documents from the orders
collection where the size of the items
array is 3.
[
{ "_id": ObjectId("..."), "orderNumber": "12345", "items": ["item1", "item2", "item3"] },
{ "_id": ObjectId("..."), "orderNumber": "67890", "items": ["item4", "item5", "item6"] },
// ... other documents
]
Explanation
- The
$match
stage is used to filter documents based on the condition that the size of theitems
array field is 3.
Use
The $size
operator in MongoDB is used for:
- Filtering documents based on the size of an array in the
$match
stage. - Retrieving documents where an array field has a specific number of elements.
Important Points
- The
$size
operator is specific to array fields. - It can be used in combination with other operators or stages to create more complex queries.
Summary
The $size
operator in MongoDB provides a straightforward way to filter documents based on the size of an array field. It is useful when you need to retrieve documents where an array has a specific number of elements. Understanding how to use the $size
operator is important for MongoDB developers working with aggregation pipelines to filter and analyze data.