• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:8 mins read
You are currently viewing MongoDB $push Operator to Update Array

This article mainly focuses on the $push operator in MongoDB and its different scenarios with other operators.

Advertisements

The $push operator is a MongoDB update operator that allows us to append new elements to an array within a document. Moreover, the $push operator can be used with various data types, including strings, numbers, and nested documents. The article will provide different examples of the $push operator along with its modifier.

Related: Update Multiple Array Elements in MongoDB

The following collection will be used to explain the MongoDB $push operator.


# Create Collection
db.student.insertMany([
      {  
         _id: 1,
         name: "Jimmy",
         course: ["Python", "Java", "MongoDB"],
         marks: []
 
      },
      {
         _id: 2,
         name: "Elena",
         course: ["Python", "Java", "MongoDB"],
         marks: []
      },
      {
         _id: 3,
         name: "Caroline",
         course: ["Python", "Java", "MongoDB"],
         marks: []
      },
      {
         _id: 4,
         name: "lan",
         course: ["Python", "Java", "MongoDB"],
        marks: []    }
   ]
)

1. Syntax of MongoDB $push operator

The following syntax of the $push operator in MongoDB looks like this:


# Syntax
{ $push: { field: value, ... } }

Here, the field specifies the name of the array to update, and values specify the value(s) to append to the array. Note that the field must be an array of the document, otherwise, the operation fails and generates the error.

2. Using $push to add a new value to an array

We have a simple demonstration here of the MongoDB $push operator that will add/append a new value to an existing array field of the specified document. Let’s consider the following query.


# Adding new value in existing array
db.student.updateOne(
   { _id: 1 },
   { $push: { marks: 99 } }
)

Here, we have the $push operator that adds a new given value to the marks array for the matched document. The output indicates that a new value has been appended to the matched document.

$push operator in MongoDB

The appended value can be seen in the marks array of the matched document.

append values array MongoDB

If you want to update multiple array elements in MongoDB, you can use the following link.

3. Using the $each modifier of $push operator to add multiple new values to the array

Next, we have the demonstration of the $each modifier of the $push operator in MongoDB that is used to add multiple elements to an array. When appending multiple values to an array field, the $each modifier should be used. Let’s consider the following below query.


# Usage of $each operator
db.student.updateOne(
   { _id: 2 },
   { $push: { marks: { 
$each: [90, 78, 50] } } }
)

Yields below output.

$push multiple values MongoDB

The matched document with the appended array elements is shown below. Note that the multiple values are added to the array field.

4. Using the $position modifier of the $push operator to add values in an array

We can use the $position modifier of the MongoDB $push operator to specify the position in the array where the new element should be added. The $position modifier takes the index value at which the new value should be placed. Here is an example.


# Usage of $position modifier
db.student.updateOne(
   { _id: 3 },
   { $push: { course: { $each: ["C++"], $position: 0 } } }
)

Here, we have applied the MongoDB $push operator to append a new value to the course array for the matched document. Furthermore, we used the $each modifier to push an array with the assigned value into the course array, and the $position modifier to insert the value at the beginning of the array as the index is set to 0. The output yielded verifies that value is added at the specified position into the array.

Now, we can see the appended elements in an array in the matched document.

$push operator in MongoDB

5. Using the $slice modifier of $push operator to limit the values to add in an array

The $slice modifier is used to limit the number of elements in the array after the new element(s) are added. Let’s take the following query about the demonstration.


#Usage of $slice modifier
db.student.updateOne(
   { _id: 4 },
   { $push: { course: { $each: ["Javascript"], $slice: -3 } } }
)

Here, the MongoDB $push operator inserts a new value to the course array for the matched document. The $each modifier used inside the $push operator pushes an array with the given element into the course array, and the $slice modifier limits the array to the last three elements as the value -3 is set to it. If the array has more than three elements, the oldest elements will be removed to keep the array length at most three.

The output shows that the document is updated with the new value in the array and sliced the array.

$push operator in MongoDB

The document array is sliced and added the new element here as presented in the following image.

$push operator in MongoDB

6. Conclusion

In conclusion, we have explored much about the $push operator and its modifiers in MongoDB with examples. By using these modifiers, we can manipulate array fields in a variety of ways.

More details about the $push operator can be found here.