MongoDB

How to Manipulate MongoDB Arrays

Arrays allow us to store multiple values within a single field, enabling us to represent the complex data structures with ease. The key feature that makes MongoDB so versatile is its support for arrays within documents. In this article, we will explore the various techniques and methods for manipulating the MongoDB arrays. Whether you need to add, update, retrieve, or delete the elements from the arrays, understanding these operations is essential for effective data management and query optimization in MongoDB.

Create the Collection and Insert the Documents to Manipulate the MongoDB Arrays

Before manipulating the MongoDB arrays, we need to create the collection and insert the documents inside it with different array fields. Here, we use the “emp” collection and insert the following documents. Note that each document has different array fields with different elements:

db.emp.insertMany([
    {
        _id:1,
        name: "John",
        projects: [ "Android", "Web"],
        bouns: [ "20", "10", "70" ],
        dept: [ "Design", "Devs"],
        status: [ {position:"Team Manager"} ]
    },
    {
        _id:2,
        name: "Alex",
        projects: [ "Android", "IOS"],
        bouns: [ "50", "80", "10" ],
        dept: [ "Accounts", "Devs"],
        status: [ {position:"QA Analyst"} ]
    },
    {
        _id:3,
        name: "Emily",
        projects: [ "Android", "Web"],
        bouns: [100, 50, 90],
        dept: [ "Analyst", "Devs"],
        status: [ {position:"Senior Manager"} ]
    },
    {
        _id:4,
        name: "Andy",
        projects: [ "Android", "ISO","Web"],
        bouns: [ "20", "40", "70" ],
        dept: [ "HR"],
        status: [ {position:"HR Manager"} ]
    },
    {
        _id:5,
        name: "Smith",
        projects: [ "Android", "Web"],
        bouns: [ "80", "10", "90" ],
        dept: [ "Design", "Devs"],
        status: [ {position:"Manager"} ]
    },
    {
        _id:6,
        name: "Ellie",
        projects: [ "Android", "Linux"],
        bouns: [ "20", "10", "70" ],
        dept: [ "Techincal", "QA"],
        status: [ {position:"Administrator"} ]
    }
])

 
Now, the output displays the document that has been inserted with their IDs in the collection successfully:


Example 1: Modify the Document’s Array Field

Now, we apply an “update” query on the array field of the specific document as shown in the following:

db.emp.updateMany({_id:2},{$set:{ projects:["Android" ,"Web", "IOS"]}})

 
In the given command, we design a query to update multiple documents within the “emp” collection in a MongoDB database. We update the documents that match a particular filter criterion using the updateMany() method. In this case, the filter condition is {_id: 2} which indicates that the query will target all documents with the “_id” field equal to 2.

For each matched document, we utilize the “$set” operator to update the “projects” field. The new value that is assigned to the “projects” field is an array containing three strings: “Android”, “Web”, and “IOS”. Consequently, the query results in the affected documents that have their “projects” field replaced with the new array of strings.

The following output represents the query results where the array has been modified:


Now, to examine the updates in the specified array, we apply the “find” query on the “_id:  2”.  The following output shows the updated value within the collection:


Example 2: Apply the $eleMatch Operator to Search the Document’s Array Field  

We can also find the specific element from the array field of the MongoDB document like the way we accomplish it in the following illustration. The $eleMatch operator is used here to match the element of the array field.

db.emp.find({ "dept": { $elemMatch: {$eq: "Analyst"} } } );

 
Now, we apply the query to retrieve the documents from the “emp” collection in a MongoDB database. We utilize the find() method which is used for searching and retrieving the data from a collection. The query contains a filter condition based on the “dept” field. In this case, the filter condition is provided as { “dept”: { $elemMatch: { $eq: “Analyst” } } }.

Here, the condition uses the $elemMatch operator to match the documents where the “dept” field is an array, and at least one element of that array matches the “Analyst” value. As long as “Analyst” is present at least once in the “dept” array, the document will be included in the query result.

The results matched with the filter condition on the execution of the query and are displayed as follows:


Example 3: Append in an Array Field of the Document Using the $push Operator

Using the $push operator, the element can also be added to the array field of the chosen document. We perform the $push operator to add the new element in the specific array field of the specified document.

db.emp.updateOne({ _id: 3 },{ $push: { bonus: {$each: [101, 200] } } })

 
The “update” operation is performed on the previous query for a specific document with the “_id” field equal to 3. We carry out the “update” operation using the updateOne method which shows that only one document is affected by this update.

Here, the update action involves the use of the $push operator to add the elements to an existing array field which is “bonus”. We then deploy the $each modifier within $push to specify that multiple elements should be added to the “bonus” array in a single update operation. Note that the two elements, 101 and 200, are added to the “bonus” array.

Hence, the document with “_id” equal to 3 has an array that is expanded with the provided new elements as represented by the following output:


Example 4: Adjust the Element’s Location in the Document’s Array Field

Furthermore, the position of the array field element can also be modified to a certain position using the $position operator with the $push operator.

db.emp.updateOne(
   { _id: 4 },
   { $push: { projects: { $each: ["Web"], $position: 1 } } }
)

 
The given query is used to modify a document in the “emp” collection again. We provide the first parameter { _id: 4 } which specifies the filter condition to identify the document to be updated. The second parameter is the update action which uses the $push operator to add the elements to the “projects” array field in the selected document.

Then, we use the $each operator to allow the addition of multiple elements to the array. In this case, it adds the “Web” string to the “projects” array. After that, we use the new operator which is $position that represents the index at which the new element should be inserted. Here, it is positioned at index 1 which indicates that it will be inserted as the second element in the “projects” array. So, this update operation adds the “Web” element to the “projects” array of the document with _id equal to 4 at the second position in the array.

The output indicates that the specified document is matched and modified accordingly:


Next, we examine the modification in the array field using the “find” query. The “Web” string is placed at the specified position as follows:


Example 5: Remove the Element of the Array Field Using the $pull Operator

Alternatively, we can remove the element from the array field of any document using the $pull operator which employs the $position operator.

db.emp.updateOne({ _id : 5 },{ $pull: { status: { position: "Manager" } } })

 
The given query again uses the updateOne method to modify a document in the “emp” collection but to remove the element from the array field. We provide the “update” operation with two parts: the filter and the update action.

Here, we specify the filter that indicates the document to be updated based on its _id field where the _id is equal to 5. The filter here targets a specific document with a particular _id. Then, we call the $pull operator which is used to remove the elements from an array that matches a specific condition. In this case, we aim to remove the elements from the “status” array where the “position” field is equal to “Manager”.

The array field is now modified by the operation that is previously performed as shown in the output:


Let’s also look at the updated document in the following output where the element of the array field is pulled out:

Conclusion

We discussed about the MongoDB array manipulation in this article with different query examples. With the knowledge gained from this comprehensive guide, we can confidently insert, update, retrieve, and delete the elements from the arrays within your MongoDB collections. Hence, manipulating the arrays in MongoDB is a powerful skill for working with complex data structures and optimizing the database queries for better performance.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.