MongoDB $size Operator Examples

Let’s look at some examples of the $size operator in MongoDB to understand the operator better.

In the following examples, we are working with:

Database: w3wiki
Collection: arrayExample
Document: three documents that contain the details in the form of field-value pairs.

Using $size Operator example

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:

Using $size Operator in the Embedded Document example

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:

MongoDB $size Operator

MongoDB $size operator finds the total number of elements present in the specified array.

Similar Reads

$size Operator in MongoDB

The $size operator in MongoDB is used to find the total number of elements in an array. It is used in aggregation pipeline stages and is important to find the size of the array within documents....

Syntax

The syntax of the $size Operator in MongoDB is:...

MongoDB $size Operator Examples

Let’s look at some examples of the $size operator in MongoDB to understand the operator better....

Important Points 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....

Contact Us