How to Add Elements into an Array in MongoDB

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

Introduction

This tutorial will explain the various ways to add elements to an array in MongoDB. Pushing, or adding, elements to an array is very useful for quickly appending a list by adding or moving items in an already existing Mongo DB document. The tutorial will explain using both negative and positive integers for the push operations, with there being more push options using a negative integer for inserting values into the array

Prerequisite

  • MongoDB must be properly installed and configured in order to add elements to an array in MongoDB.

  • A basic understanding of how arrays functions.

Pushing Elements to an Array

This section will explain how to push an element to an array with a $push operator, such as an update operation.

First, create a sample dataset, with animals, as follows:

1
2
3
4
5
6
7
> use animaldb
switched to db animaldb
> db.animal.insert({
...       "_id": "100",
...       "animalArray": ['dog', 'lizard', 'lion']
...   });
WriteResult({ "nInserted" : 1 })

Now verify the insert process with the: db.animal.find({_id: "100"}); command.

The result should resemble the following.

1
{ "_id" : "100", "animalArray" : [ "dog", "lizard", "lion" ] }

Now add another animal into the animalArray. In this example, execute the following command to add ‘cat’:

1
2
3
4
5
6
7
8
db.animal.update(
      { "_id": "100" },
      {
          $push: {
              animalArray: "cat"
          }
      }
  );

The results should resemble the following:

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

To verify cat was successfully added into the animalArray as an element, execute the following command:

db.animal.find({_id: "100"}).pretty();

The output should be as follows:

1
2
3
4
5
6
7
8
9
{
        "_id" : "100",
        "animalArray" : [
                "dog",
                "lizard",
                "lion",
                "cat"
        ]
}

The results confirm the $push operator appended the word ‘cat’ at the end of the animalArray.

Pushing Elements at the start of the Array

The previous section explained how to appended a new element at the end of the array. This section will cover how to push the element ‘cow’ at the beginning of the array.

This action is performed with the following command:

1
2
3
4
5
6
7
8
9
10
11
> db.animal.update(
      { "_id": "100" },
      {
          $push: {
              animalArray: {
                  $each: ['cow'],
                  $position: 0
              }
          }
      }
  );

The successful update operation can then be verified with the db.animal.find({_id: "100"}).pretty(); command.

The output should resemble the following:

1
2
3
4
5
6
7
8
9
10
{
        "_id" : "100",
        "animalArray" : [
                "cow",
                "dog",
                "lizard",
                "lion",
                "cat"
        ]
}

The above command used the operator $position. As the name implies, this command positions the element within the array as defined by the user. Also note the positive integer used for the value for the $position will be pushed from the left, or beginning, of the array.

Pushing Elements at the end of the Array

The previous section explained how to insert an element into the beginning of the array using a positive integer for the value of the $position operator. This section will explain how to push the elements using a negative integer for the value, as shown here:

1
2
3
4
5
6
7
8
9
10
db.animal.update(
      { "_id": "100" },
      {
          $push: {
              animalArray: {
              $each: ['goat'],
              $position: -1
          }
      }
  });

The output should resemble the following:

1
2
3
4
5
6
7
8
9
10
11
{
        "_id" : "100",
        "animalArray" : [
                "cow",
                "dog",
                "lizard",
                "lion",
                "goat",
                "cat"
        ]
}

Note that by using a -1 for the value, ‘goat’ was inserted in the second to the last position of the elements list with the last element having at position of ‘0’.

Pushing Multiple Elements

This section will cover how to add, or push, multiple elements into the array.

First, create another array inside the animal document as follows:

1
2
3
4
db.animal.insert({
      "_id": "101",
      "animalArray": ["sheep","turtle","monkey"]
  });

A new document should now be created with the following details:

1
{ "_id" : "101", "animalArray" : [ "sheep", "turtle", "monkey" ] }

Now add multiple element to the new document with the following command:

1
2
3
4
5
6
7
8
9
10
11
db.animal.update(
      { "_id": "101" },
      {
          $push: {
              animalArray: {
                  $each: ['dove', 'eagle', 'hawk'],
                  $position: -2
              }
          }
      }
  );

Notice in the above code, as the elements [‘dove’, ‘eagle’, ‘hawk’] are pushed, this array can be considered as one element. This causes ‘dove’ to be pushed, or moved, to the specified position of -2, followed by eagle and hawk, respectively. It should be noted that the elements will be inserted into the array in order.

CONCLUSION

This tutorial explain the various ways to add elements to an array in MongoDB. The tutorial explained how to push elements to an array with a $push operator, such as used in an update operation. It then explained how to create a sample dataset, add elements into the array and then verify the insert process. The article also covered how to push elements at the start of the array, at the end of the array and then how to push multiple elements. Remember that when a negative integer is used as the value it will push elements at the end of the array and a positive integer will push from the left, or beginning, of the array.

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.