Array operator in MongoDB

Array Operator in MongoDB

The array operator in MongoDB is used to query for array fields. We’ve other fields type like String, Numeric and Boolean values. These are common types and have the same kind of implementation. But the Array is a little different than others. We will be learning common use cases and implementation of the Array operators here. Most frequently used array operators in MongoDB are $push, $all, $size etc.

The most frequently used array operator in MongoDB is $push. We can use $push operator to add an element to an existing array field. We can also change a field to an array field if it was previously a different type. Let’s see both the examples below:

Add an element using $push operator

Consider the following document.

{
        "_id" : ObjectId("631d6681927abfef4bc0c1e9"),
        "name" : "Anil",
        "department" : "HR",
        "salary" : 50000,
        "address" : {
                "city" : "Pokhara",
                "area" : "Lakeside"
        },
        "bonus" : 50000,
        "hobbies" : [
                "cricket"
        ]
}

In the above document, we can see that the hobbies field is an array field and has two elements.

We can add another element in that field by using the $push operator. See the query below:

db.employee.updateOne({"name": "Anil"}, {"$push":{ "hobbies": "singing"}})

The query above adds an element singing to the hobbies list.

Let’s check using the find query.

{
        "_id" : ObjectId("631d6681927abfef4bc0c1e9"),
        "name" : "Anil",
        "department" : "HR",
        "salary" : 50000,
        "address" : {
                "city" : "Pokhara",
                "area" : "Lakeside"
        },
        "bonus" : 50000,
        "hobbies" : [
                "cricket",
                "singing"
        ]
}

We can see that singing is added to the hobbies list.

Add multiple elements using $push operator

We can also add multiple elements in the array field using the $push operator. See the query below:

db.employee.updateOne({"name": "Anil"}, {"$push":{ "hobbies": {"$each": ["dancing", "teaching"]}}})

The above query adds each element one by one to the hobbies field. Let’s verify our data by using the find query.

{
        "_id" : ObjectId("631d6681927abfef4bc0c1e9"),
        "name" : "Anil",
        "department" : "HR",
        "salary" : 50000,
        "address" : {
                "city" : "Pokhara",
                "area" : "Lakeside"
        },
        "bonus" : 50000,
        "hobbies" : [
                "cricket",
                "singing",
                "dancing",
                "teaching"
        ]
}

Cool!

New hobbies are added to the existing hobbies list.

Now, let’s explore more with different queries.

Find employees by hobby

In this section, we will query employee collection to find an employee whose one of the hobbies is cricket.

The query looks like this:

db.employee.find({"hobbies": "cricket"}).pretty()

This query list the following document:

{
        "_id" : ObjectId("631d6681927abfef4bc0c1e9"),
        "name" : "Anil",
        "department" : "HR",
        "salary" : 50000,
        "address" : {
                "city" : "Pokhara",
                "area" : "Lakeside"
        },
        "bonus" : 50000,
        "hobbies" : [
                "cricket",
                "singing",
                "dancing",
                "teaching"
        ]
}

What the query we’ve executed doing is, checking all the documents that match one of the elements in the hobbies array field. Though, the query does not specify that hobbies has to be an array. So this looks like we’re querying a field that could just have a string as a value.

Now, let’s differentiate and look for the document that hobbies is specifically an array field with the following query:

db.employee.find({"hobbies": ["cricket"]}).pretty()

As a layman’s term, the result should’ve returned the documents that match cricket in the hobbies array field. But the query returns nothing.

This is because MongoDB is looking for a document where the value of the array field is a single element cricket. Because, without any special operators, it will look for an exact match.

The order of elements in an array field query does matter

Now, the question is, does the order of elements in an array field query matter? The answer is yes. Let’s check this out with the following query.

First, I will copy the exact values from the hobbies field and execute the query.

db.employee.find({"hobbies": ["cricket","singing","dancing","teaching"]}).pretty()

The above query returns the document where the hobbies field has the exact same hobbies with the same order.

But, when I change the order of the hobbies value and execute the query:

db.employee.find({"hobbies": ["singing","cricket","dancing","teaching"]}).pretty()

This query returns nothing.

Hence, it is confirmed that the order of elements in an array field of the MongoDB document does matter.

Find documents in MongoDB that contain more than one element in an array field

Now, we will have another question that is, how do we find all documents that contain more than one hobbies without caring about the order of array elements?

MongoDB Query Language (MQL) has a great operator for that called $all.

$all operator in MongoDB array field

This operator returns a cursor with all documents in which the specified array field contains all the given elements regardless of their order in the array.

Syntax:

{<array field>: {"$all": <number value>}}

Let’s see an example with the following query:

db.employee.find({"hobbies": {"$all":["singing","cricket","dancing","teaching"]}}).pretty()

This query returns the documents that match at least one element in the hobbies field. The order does not matter and also we don’t have to add all the elements from an array field.

Find documents in MongoDB that contain exactly four hobbies which include all the hobbies given in the query array.

In this section, we will learn to limit our query match condition.

For example, instead of matching all the hobbies of an employee, I want to find employees whose hobbies are exactly four that should match any hobbies given in the query array.

$size operator in MongoDB array field

This operator returns a cursor with all documents where the specified array field is exactly the given length.

Syntax:

{<array field>: {"$size": <number value>}}

Let’s take an example of $size operator along with $all operator.

db.employee.find({"hobbies":{"$size":4,"$all":["dancing","teaching"]}}).pretty()

This returns the following output:

{
        "_id" : ObjectId("631d6681927abfef4bc0c1e9"),
        "name" : "Anil",
        "department" : "HR",
        "salary" : 50000,
        "address" : {
                "city" : "Pokhara",
                "area" : "Lakeside"
        },
        "bonus" : 50000,
        "hobbies" : [
                "cricket",
                "singing",
                "dancing",
                "teaching"
        ]
}

Conclusion

In this post, we learned about different array operators in MongoDB apart from $push operator. We learned the $size and $all operator along with their use case and example.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments