MongoDB – $size Operator
Last Updated :
23 Apr, 2024
MongoDB $size operator finds the total number of elements present in the specified array. $size operator is one of the array expression operators and is also used in aggregation pipeline stages.
Syntax
{ $size: <expression> }
Here, the given arguments must be a valid expression until it resolves to an array. If the argument of this operator is missing or the argument does not resolve to an array, then this operator will give errors.
MongoDB $size Operator Examples
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: arrayExample
Document: three documents that contain the details in the form of field-value pairs.
Example 1: Using $size Operator
In this example, we are going to find the size of the number1 field( whose value is an array) using a $size operator.Â
Query:
db.arrayExample.aggregate([
... {$match: {name: "Lolo"}},
... {$project: {number1Size: {$size: "$numbers1"}}}])
Output:
Example 2: Using $size Operator in the Embedded Document
In this example, we are going to find the size of the favGame.indoorGames field( whose value is an array) using a $size operator.Â
Query:
db.arrayExample.aggregate([
... {$match: {name: "Piku"}},
... {$project: {resultSize: {$size: "$favGame.indoorGames"}}}])
Output:
Key Takeaways About $size Operator
- The $size operator in MongoDB is used to find the total number of elements present in a specified array.
- If the argument of the $size operator is missing or does not resolve to an array, errors may occur.
- It is an aggregation operator that can be used in the aggregation pipeline stages.
- The $size operator can be used to find the size of arrays in documents, allowing for efficient data analysis and manipulation.
Share your thoughts in the comments
Please Login to comment...