Update MongoDB Array

Introduction

One important way that MongoDB differs from traditional relational database models is its extensive use of arrays. Arrays can be embedded within MongoDB documents, and MongoDB provides a number of array operators to help you access and manipulate your array data. When you work with array data in MongoDB, you’ll find that updating an array or an element of an array is a common task. In this article, we’ll show you how to update a MongoDB array and provide some helpful examples to use as a guide.

Prerequisite

Before diving into this tutorial, make sure that MongoDB server is installed and configured on your system.

MongoDB Sample Document

The first thing we need to do is to create a MongoDB sample document that we can use throughout our tutorial. We’ll need to perform the following steps:

  1. Log in to the MongoDB shell.
  2. Create a database called mobiledb.
  3. Create a collection named mobile and insert documents into it.

Let’s look at the SQL needed to handle these steps:

> use mobiledb
switched to db mobiledb
> db.mobile.insertMany( [
...  { _id : "1001", brand : "Samsung", model: ["Galaxy Note10 Lite", "Galaxy S10 Lite", "Galaxy A01", "Galaxy A71"] },
...  { _id : "1002", brand : "Iphone", model: ["Iphone3G", "Iphone3GS", "Iphone4", "Iphone4S"] },
...
... ] );
{ "acknowledged" : true, "insertedIds" : [ "1001", "1002" ] }
>

We can confirm that our insert operation was successful using the following command: db.mobile.find().pretty()

We should see output that looks like the following:

> db.mobile.find().pretty()
{
        "_id" : "1001",
        "brand" : "Samsung",
        "model" : [
                "Galaxy Note10 Lite",
                "Galaxy S10 Lite",
                "Galaxy A01",
                "Galaxy A71"
        ]
}
{
        "_id" : "1002",
        "brand" : "Iphone",
        "model" : [
                "Iphone3G",
                "Iphone3GS",
                "Iphone4",
                "Iphone4S"
        ]
}
>

We can see that the documents for the Samsung and Iphone brands both have an array field named model. In our examples, we’ll be focusing on this particular field.

Updating MongoDB Array

In this section, we’ll show you some different ways to update a MongoDB array.

Insert New Element by Updating a MongoDB Array

Our first example will show you how to insert an element using the update method and supplying an exact position of a MongoDB array.

Here’s what the command syntax looks like:

{"the_document_name.$.array_document.position":"new_value"}});

Lets use this command to update our document:

> db.mobile.update({brand:"Samsung"},{$set:{"model.4":"Galaxy A51"}});

The code shown above will attempt to update and add a new element in the fourth index position of the ‘model’ array. It will assign a new value of ‘Galaxy A51’ to this element.

After executing this command, we should see something like the following:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

We can verify that our update was a success using the Mongo shell:

> db.mobile.find({brand:"Samsung"}).pretty()
{
        "_id" : "1001",
        "brand" : "Samsung",
        "model" : [
                "Galaxy Note10 Lite",
                "Galaxy S10 Lite",
                "Galaxy A01",
                "Galaxy A71",
                "Galaxy A51"
        ]
}
>

We can see that the ‘Galaxy A51’ was placed as the last element of the ‘model’ array. Our update was successful.

Updating an Exact Element of MongoDB Array

In the previous section, we inserted a new MongoDB element into an array using the update method. Now we’ll try updating an existing element within a MongoDB array.

The basic syntax will be the same as the previous example:

{"the_document_name.$.array_document.position":"new_value"}});

Let’s use the above syntax to update an existing array element in our document:

> db.mobile.update({brand:"Iphone"},{$set:{"model.2":"IphoneX"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

The above command will update the third (index position ‘2’) element within the model array, which is inside the Iphone document. We’ll give it a new value of ‘IphoneX’.

Now we can see if the update was a success:

> db.mobile.find({brand:"Iphone"}).pretty()
{
        "_id" : "1002",
        "brand" : "Iphone",
        "model" : [
                "Iphone3G",
                "Iphone3GS",
                "IphoneX",
                "Iphone4S"
        ]
}
>

We can see that the original value of ‘Iphone4’ was replaced with a new value of ‘IphoneX’.

Conclusion

If you’re planning to store and manage data in MongoDB, it’s important to know how to work with arrays. Being able to insert a new element into an array or update the value of an existing array are common tasks for developers who work with MongoDB. In this article, we showed you several examples that illustrate how to update a MongoDB array. With our examples and instructions, you should have no problem updating arrays in your own MongoDB implementation.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.