MongoDB $size Operator: Filter Documents Based on Array Size

As we know, MongoDB documents have the ability to possess arrays as field values, these arrays may enclose multiple elements. The $size operator can clubbed with other MongoDB methods like find(), findOne(), etc to filter documents based on the number of elements inside an array.

In this article, we will explore the $size operator and its syntax and demonstrate it with various examples. Let’s get started.

Also Read: $gt(Greater than) and $lt(Less than) Operators in MongoDB

MongoDB $size Operator

The $size operator in MongoDB helps us filter documents based on a specific array within them that matches the number of elements given by the argument. The number of elements and arrays can be manually specified.

Let us take a quick look at the syntax of MongoDB’s $size operator.

Syntax:

db.collection.find( { field: { $size: 1 } } )

Parameters:

  1. Here “collection” is the collection name where we are looking for the documents.
  2. “find()” is the method we are using to get the documents.
  3. In “{ field: { $size: n } }”, the field represents an array field, and n is the number of elements that must be in the array for the match.

Return:

It returns documents that contain the defined number of elements in the specified array field.

Important:

The $size operator does not support value ranges. Create a counter field that you increment when you add elements to a field to select documents based on fields with different numbers of elements.

Queries cannot use indexes for the $size portion of a query, however, indexes can be allowed to be used for the other portions of a query if applicable.

Examples of MongoDB $size Operator

In this section, we will be demonstrating the use of the $size operator in the MongoDB shell to filter documents.

We have already created a collection “drones” possess numerous documents for demonstration.

Following are the documents inside “drones”: 

> db.drones.find().pretty()
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0c"),
        "utility" : [
                "Natural Resource Exploration",
                "Remote sensing",
                "Real estate and construction",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "Nimbari Gryphon Medeta 65",
        "price" : 77500,
        "weight" : "77 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection",
                        "Water Inspection",
                        "Cinematography"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0d"),
        "utility" : [
                "Natural Resource Exploration",
                "Remote sensing",
                "Real estate and construction",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "X-Strimmer Eye",
        "price" : 23500,
        "weight" : "24 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Precision Agriculture",
                        "Cinematography"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0e"),
        "utility" : [
                "Natural Resource Exploration",
                "Remote sensing",
                "Real estate and construction",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "Khai Balemosh Shefqa TRX",
        "price" : 120500,
        "weight" : "80 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0f"),
        "utility" : [
                "Natural Resource Exploration",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "Sifinist Croma AX",
        "price" : 99500,
        "weight" : "97 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection",
                        "Water Inspection",
                        "Videography"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf10"),
        "utility" : [
                "Remote sensing",
                "Real estate and construction",
                "Recreation"
        ],
        "onSale" : false,
        "name" : "Drovce Finnifield FR-7",
        "price" : 87600,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "polysterene",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection",
                        "Water Inspection",
                        "Videography"
                ]
        }
}

Here, we have used the pretty() function which is used in MongoDB to format the query results with a proper indentation and produce readable output that looks like JSON which makes it easier to view and understand the data.

Example 1: Matching Top-Level Arrays Using $size Operator in MongoDB

This example is going to be extremely simple. Here we will be using the $size operator to match the top-level arrays within documents based on the number of elements they possess.

Top-level arrays are the arrays that are not nested within subdocuments or another array, i.e., it is at the base or top level.

Let’s try to get all those documents whose “utility” array field is of the size 3 i.e. having 3 elements. Given below is the query for that.

> db.drones.find( { utility: { $size: 3 } } ).pretty()
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0f"),
        "utility" : [
                "Natural Resource Exploration",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "Sifinist Croma AX",
        "price" : 99500,
        "weight" : "97 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection",
                        "Water Inspection",
                        "Videography"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf10"),
        "utility" : [
                "Remote sensing",
                "Real estate and construction",
                "Recreation"
        ],
        "onSale" : false,
        "name" : "Drovce Finnifield FR-7",
        "price" : 87600,
        "weight" : "13 kilograms",
        "additionalDetails" : {
                "material" : "polysterene",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection",
                        "Water Inspection",
                        "Videography"
                ]
        }
}

See the documents we acquired, having exactly 3 elements in their ‘utility’ array field exhibiting a successful $size operation.

Example 2: Matching Embedded Array Fields Using $size Operator in MongoDB

This is an interesting one, although a little complex. In this example, we are operating on an array field that is embedded inside a document. 

Let’s try to get all those documents that have an array field named “moreUses” embedded inside the “additionalDetails” field, with a size of 2 i.e. having 2 elements.

> db.drones.find( { "additionalDetails.moreUses": { $size: 2 } } ).pretty()
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0d"),
        "utility" : [
                "Natural Resource Exploration",
                "Remote sensing",
                "Real estate and construction",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "X-Strimmer Eye",
        "price" : 23500,
        "weight" : "24 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Precision Agriculture",
                        "Cinematography"
                ]
        }
}
{
        "_id" : ObjectId("61673f46b34f185eb7b2bf0e"),
        "utility" : [
                "Natural Resource Exploration",
                "Remote sensing",
                "Real estate and construction",
                "Recreation",
                "Delivery"
        ],
        "onSale" : false,
        "name" : "Khai Balemosh Shefqa TRX",
        "price" : 120500,
        "weight" : "80 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Precision Agriculture",
                        "Land Inspection"
                ]
        }
}

Here we got all those documents where the “moreUses” array field has a length of 2. This justifies that we can efficiently use the $size operator in the complex embedded array fields as well.

This is not the end, you can also use the $size operator in your project by using it within the aggregation pipeline stages that can take expressions like $project, $match, etc. Click here to get more information about it.

Conclusion

The size operator in MongoDB gives it additional power to perform operations based on the number of elements inside a specific array present in its documents. It can be used on both top-level arrays, i.e., arrays embedded directly in the document or embedded arrays, i.e., arrays embedded in the subdocument or another array. After reading this article, we hope you got answers to all your questions related to the MongoDB $size operator.

Read More:

Reference

$size — MongoDB Manual

Aneesha S
Aneesha S
Articles: 171