Add Element Array in MongoDB Document

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Unlike a typical relational database, MongoDB has a flexible document structure in which a field can have an array as its value. It’s important to know how to manage data within these arrays. In this article, we’ll focus on the task of adding an element to an array. We’ll show you how to add an element to an array in a MongoDB document, with simple examples to demonstrate how it’s done.

Prerequisite

If you plan to follow along with the steps outlined in this article, you’ll need to have the following software installed and configured:

Add Element Array Using $Push Command

In MongoDB, we can add an element to an array using the $push command. Let’s consider the following document:

1
2
3
4
5
6
7
8
9
10
11
> db.movie.insert({_id:"101",movies:['titanic','terminator','jason bourne']})
WriteResult({ "nInserted" : 1 })
> db.movie.find().pretty()
{
        "_id" : "101",
        "movies" : [
                "titanic",
                "terminator",
                "jason bourne"
        ]
}

The commands shown above demonstrate how to create a collection and a document that contains an array. In this example, the array is called movies.

If we want to add another movie title into the movies array, we can use the following command:

1
2
3
4
5
6
7
8
db.movie.update(
    {_id: "101"},
    {
        $push: {
            movies : "batman"
        }
    }
)

MongoDB responds with the following output: WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }). This tells us that one document matched the criteria defined in our command, and one document was modified.

To verify that our $push command was successful, we can query our movie collection once again:

1
2
3
4
5
6
7
8
9
10
> db.movie.find().pretty()
{
        "_id" : "101",
        "movies" : [
                "titanic",
                "terminator",
                "jason bourne",
                "batman"
        ]
}

We can see that batman was pushed, or added, to the end of the movie array.

NOTE: We use the .pretty() option to indent the JSON response from MongoDB. This makes the document more readable.

Adding an Element at the Beginning of the Array

In the previous section, we observed that elements are added to the end of an array by default. For our next example, let’s try adding the element at the beginning of the array:

1
2
3
4
5
6
7
8
9
10
11
db.movie.update(
    {_id: "101"},
    {
        $push: {
            movies: {
                $each: ['coming back to america'],
                $position: 0
            }
        }
    }
)

The above query will respond with the following output: WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }). This output implies that we updated the movies array successfully.

We can confirm that the operation was successful using a simple query:

1
2
3
4
5
6
7
8
9
10
11
> db.movie.find().pretty()
{
        "_id" : "101",
        "movies" : [
                "coming back to america",
                "titanic",
                "terminator",
                "jason bourne",
                "batman"
        ]
}

How were we able to ensure that the element was added at the beginning of the array? Notice that we called the $position operator in our $push command– this operator tells MongoDB where the new element should be placed inside the array. In this case, the element was inserted at the left, or beginning, of the array.

Adding Multiple Elements

In our next example, we’ll show how to add multiple elements to an array. We’ll be using the same principle as we did in the previous section.

Let’s see what the command looks like:

1
2
3
4
5
6
7
8
9
10
11
db.movie.update(
    {_id: "101"},
    {
        $push: {
            movies: {
                $each: ['dolittle','madagascar','avengers'],
                $position: -2
            }
        }
    }
)

The example shown above will add the specified elements two steps to the right because we used a - sign in the value of $position. The order of the specified elements will be preserved when pushed into the array.

The output looks like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
> db.movie.find().pretty()
{
        "_id" : "101",
        "movies" : [
                "coming back to america",
                "titanic",
                "terminator",
                "dolittle",
                "madagascar",
                "avengers",
                "jason bourne",
                "batman"
        ]
}

Conclusion

One key feature of MongoDB is its flexible document structure, which allows fields to contain arrays as values. If you need to add an element to an existing array in MongoDB, it’s easy to accomplish the task with the help of the $push operator. In this article, we showed you how to add an element to an array in a MongoDB document, and we showed you a number of examples to illustrate the process. With our step-by-step instructions, you’ll have no problem working with arrays in your own MongoDB documents.

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.