MongoDB $size Operator

MongoDB provides different types of array expression operators that are used in the aggregation pipeline stages and $size operator is one of them. This operator is used to find the total number of elements present in the specified array.

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.

 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.

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. 

db.arrayExample.aggregate([
... {$match: {name: "Lolo"}},
... {$project: {number1Size: {$size: "$numbers1"}}}])

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. 

db.arrayExample.aggregate([
... {$match: {name: "Piku"}},
... {$project: {resultSize: {$size: "$favGame.indoorGames"}}}])

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.