How to Update Push Array in MongoDB

Tahseen Tauseef Feb 02, 2024
  1. Operators in MongoDB
  2. $push Operator in MongoDB
  3. Push Elements to an Array in MongoDB
  4. Push Elements at the Start of the Array in MongoDB
  5. Push Elements at the End of the Array in MongoDB
  6. Push Multiple Elements in MongoDB
How to Update Push Array in MongoDB

This instructional post will show you how to add elements to an array in MongoDB using various techniques. Pushing or adding elements to an array is extremely handy for quickly appending a list by adding or moving objects in an existing MongoDB document.

The lesson will teach how to use both negative and positive integers for push operations, with a negative integer providing additional push possibilities for putting data into the array.

Prerequisite:

  1. MongoDB must be appropriately installed and configured to add elements to an array in MongoDB.
  2. A basic understanding of how arrays function.

Let’s first look at the table of contents for this article.

  1. Operators in MongoDB
  2. $push operator in MongoDB
  3. Pushing elements to an array
  4. Pushing elements at the start of the array
  5. Pushing elements at the end of the array

Operators in MongoDB

Operators are special symbols or keywords that tell a compiler or interpreter how to do mathematical or logical operations. The query operators extend MongoDB’s capability by allowing developers to write complicated queries to interact with data sets relevant to their applications.

The following are the various types of operators in MongoDB.

  1. Query and Projection Operators - Query operators aid in discovering data in a database, whereas projection operators alter how data is shown.
  2. Update Operators - Update operators allow you to change or add data to your database.
  3. Aggregation Pipeline Stages - Available aggregation stages for Aggregation Pipeline.
  4. Aggregation Pipeline Operators - Aggregation pipeline operations have a collection of operators available to define and manipulate documents in pipeline stages.
  5. Query Modifiers - Query modifiers determine how queries will be executed.

$push Operator in MongoDB

In MongoDB, the $push operator is used to attach a value to an array. The $push operator is an update operator.

If the supplied field is not in the document being changed, the $push operator creates it as a new field with the specified value as its element. The operation failed if the updating field was not of the array type.

When updating, the $push operator appends the entire array as a single element if the value is an array. Use the $push operator with the $each modifier to add each value element individually.

Syntax:

db.collection.update( <query>,{ $push: { <field>: <value> } })

Example of MongoDB $push operator:

If you want to append 95 to the array field accomplished when the condition subjects is maths, we may use the MongoDB command below.

db.student.update( { "subjects" : "maths" },{ $push: { "achieve": 95 } });

Because the criterion described in the preceding example matches this action, the value 95 will be appended to the array accomplished.

To see the newly updated document:

db.student.find().pretty();

The output of the query given above can be seen in this screenshot.

use push operator

Example of MongoDB $push when the field is not an array:

If you wish to add 2 to the sem column, which is not an array type field, we may use the MongoDB command below.

db.student.update( { "subjects" : "maths" },{ $push: { "sem": 2 } });

Because the sem field in the above example is not of the array type, the operation will fail and produce the following result.

Cannot apply $push/$push All modifier to non-array

Push Elements to an Array in MongoDB

This section shows how to use a $push operator, such as an update operation, to add an element to an array.

First, create a sample dataset with fruits, as follows.

use fruitdb
switched to db fruitdb
db.fruit.insert({
      "_id": "100",
      "fruitArray": ['mango', 'banana', 'orange']
   });
WriteResult({ "nInserted" : 1 })

Now verify the insert process with the following command.

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

The result should resemble the following.

Push Elements to an Array in MongoDB

Now add another fruit into the fruitArray. In this example, execute the following command to add pineapple.

db.fruit.update(
      { "_id": "100" },
      {
          $push: {
              fruitArray: "pineapple"
          }
      }
  );

The results should resemble the following.

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

Execute the following command to verify that pineapple was successfully added into the fruitArray as an element.

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

The output should be as follows.

Push Elements to an Array in MongoDB 2

The results demonstrate that the $push operator inserted the word pineapple to the end of the fruitArray.

Push Elements at the Start of the Array in MongoDB

The preceding section described how to attach a new element to the start of an array. This section will demonstrate how to insert the element grapes at the beginning of the array.

The following command is used to carry out this action.

db.fruit.update(
      { "_id": "100" },
      {
          $push: {
              fruitArray: {
                  $each: ['grapes'],
                  $position: 0
              }
          }
      }
  );

The following command can then confirm that the update procedure was successful.

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

The output should resemble the following.

Push Elements at Start of the Array in MongoDB

The operator $position was used in the preceding operation. As the name says, this command places the element within the array as defined by the user.

Also, keep in mind that the positive integer used for the $position value will be pushed from the array’s left or beginning.

Push Elements at the End of the Array in MongoDB

The preceding section demonstrates how to insert an element at the beginning of an array using a positive integer as the value of the $position operator. This part will teach you how to push the items using a negative integer as the value, as demonstrated here.

db. fruit.update(
      { "_id": "100" },
      {
          $push: {
              fruitArray: {
              $each: ['apple'],
              $position: -1
          }
      }
  });

The output should resemble the following.

Push Elements at End of the Array in MongoDB

Using a -1 for the value, apple was put in the second to last position of the elements list, with the last element at position 0.

Push Multiple Elements in MongoDB

This section shows how to insert or push multiple elements into an array.

First, inside the fruit document, add another array.

db. fruit.insert({
      "_id": "101",
      "fruitArray": ["strawberry","guava","lemon"]
  });

A new document should be generated with the following information.

Push Multiple Elements in MongoDB

Now, use the following command to add numerous elements to the new document.

db.fruit.update(
      { "_id": "101" },
      {
          $push: {
              fruitArray: {
                  $each: ['pear', 'cherry', 'lime'],
                  $position: -2
              }
          }
      }
  );

As the items ['pear', 'cherry', and 'lime'] are pushed in the above code, this array may be viewed as one element. This pushes or moves pear to the stated position of -2, followed by cherry and lime, in that order.

It should be noticed that the elements will be added to the array in the order given.

This article walked you through the various methods for adding elements to an array in MongoDB. First, the lesson demonstrated utilizing a $push operator to add elements to an array, such as an update operation.

It was then demonstrated how to generate a sample dataset, insert elements into the array, and finally test the insert process. The article also discussed how to push elements at the beginning, middle, and end of an array and how to push multiple elements.

Remember that a negative integer as the value will push elements to the array’s end, whereas a positive integer would push elements from the array’s left or beginning.