Table of contents
1.
Introduction
2.
What is $push operator in MongoDB?
2.1.
Syntax of $push in MongoDB
2.2.
Parameters
3.
Example of MongoDB $push operator
3.1.
Combining $push with Other Operators for Updates
3.2.
Appending values into array
4.
List of $push Operator Modifiers in MongoDB
5.
Frequently Asked Questions
5.1.
Can the $push operator add multiple values to an array at once?
5.2.
What happens if the array field does not exist in the document?
5.3.
Is it possible to conditionally add values to an array using the $push operator?
5.4.
Are there any limitations to the $push operator in MongoDB?
6.
Conclusion
Last Updated: Jan 14, 2025
Easy

$push Operator in MongoDB

Author Lekhika
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The $push operator in MongoDB is used to append elements to an existing array field in a document. It is particularly useful when you want to add new values to an array without modifying the existing elements. The $push operator ensures atomicity and provides efficient ways to modify arrays without requiring additional read-write operations.

In this article, we will learn about the $push Operator in Mongodb.

$push Operator in MongoDB

What is $push operator in MongoDB?

In MongoDB, the $push operator is used to appends a specified value to an array.If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.

At the time of updating if the value itself is an array, the $push operator appends the whole array as a single element.If you want to add each element of the value separately, the $push operator can be used with the $each modifier

Syntax of $push in MongoDB

The syntax of the $push operator in MongoDB is,

db.collection.updateOne(
   { <query> },
   { $push: { <field1>: <value1>, ... } }
)

Parameters

Name name of the column or field in the document.
valueThese are the values to be specified for the fields or columns.
queryThe query may be an expression or condition or criteria.

Example of MongoDB $push operator

If we want to append 95 to the array field achieve against the condition subjects is "gkn", the following mongodb command can be used -

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

 

Here in the above example the value 95 will be append into the array achieve, because the condition mentioned is matching for this operation.

To see the newly updated document -

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

 

Output:

       "_id" : 1,
        "achieve" : [
                70,
                87,
                90,
                90,
                65,
                81,
                95
        ],
        "sem" : 1,
        "subjects" : [
                "phys",
                "chem",
                "maths ",
                "gkn",
                "stat",
                "astro"
]

Combining $push with Other Operators for Updates

Modifiers of Push Operator in MongoDB

MongoDB provides various modifiers that can be used in conjunction with the $push in mongoDB to modify the behavior of the operation. The syntax of the $push operator with modifiers is,

db.collection.updateOne
{ <query> },
{ $push: { <field1>: { <modifier1>: <value1>, ... }, ... }}
)

 

The modifiers used along with the $push in mongoDB are executed in a defined order. The modifiers in the order of their execution are:

  1. The $each modifier allows appending multiple values to an array field. It accepts an array of values as input.
     
  2. The $sort modifier performs sorting operations in ascending or descending order as specified. This operator can only be used with the $each modifier.
     
  3. The $position modifier allows you to specify the index at which the new elements should be inserted in the array. It accepts a numeric value representing the desired index.
     
  4. The $slice modifier is used to limit the number of elements in the array field after performing the push operation. It accepts a numeric value which is the desired size of the array.
     
  5. The $addToSet modifier is used to ensure that the pushed value is unique within the array. The values specified will not be added to the array if the values already exist in the array.

Appending values into array

There are three type of appending the values in array:

  • Appending a single value to an array
     
  • Appending multiple values to an array
     
  • Appending multiple values to an array in the nested/embedded document

 

1. Appending a single value to an array:
In this example, we are appending a single value, i.e., “C++” to an array field, i.e., language field in the document that satisfy the condition(name: “Rohit”).
Syntax:

db.contributor.update({name: "Rohit"}, {$push: {language: "C++"}})

To append a single value, let's say orange, to the favorites array, we can use the following update query,

db.users.updateOne
 { "_id": 1 },
{ $push: { "favorites": "orange" } }
)

 

In the above query, the document is fetched using the _id. The favorites is the array field, and orange is the value that is to be pushed to the array. The modified document after the above using the operator push in MongoDB is,

{
   "_id": 1,
   "name": "Hari",
   "favorites": ["apple", "banana", "orange"]
}

 

2. Appending multiple values to an array:

In this example, we are appending multiple values, i.e., [“C”, “Ruby”, “Go”] to an array field, i.e., language field in the document that satisfy the condition(name: “Sumit”).

Syntax:

db.contributor.update({name: "Sumit"}, {$push: {language: {$each: ["C", "Ruby", "Go"]}}})

 

To append multiple values, let's say ["mango", "grape"], to the favorites array, we can use the $each modifier. The following query shows this,

db.users.updateOne(
{ "_id": 1 },
{ $push: { "favorites": { $each: ["mango", "grape"] } } }
)

 

After executing the above query, the modified document is,

{
   "_id": 1,
   "name": "John",
   "favorites": ["apple", "banana", "orange", "mango", "grape"]
}

 

3. Appending multiple values to an array in the nested/embedded document:

In this example, we are appending multiple values, i.e., [89, 76.4] to an array field, i.e., personal.semesterMarks field of a nested/embedded document.

Syntax:

db.contributor.update({name: "Sumit"}, {$push: {"personal.semesterMarks": {$each: [89, 76.4]}}})

List of $push Operator Modifiers in MongoDB

The $push operator in MongoDB appends a value to an array field. It can be enhanced with several modifiers to customize the behavior when adding elements. Below are the main modifiers:

  • $each:
    Appends multiple values to an array at once.
  • $slice:
    Limits the number of elements in the array after the $push operation. Positive numbers retain the last N elements, and negative numbers retain the first N.
  • $sort:
    Sorts the array elements after the $push operation. Can be in ascending (1) or descending (-1) order.
  • $position:
    Specifies the position in the array where the new values should be inserted. By default, values are appended to the end.

 

Frequently Asked Questions

Can the $push operator add multiple values to an array at once?

Yes, the $push operator supports the use of the $each modifier, which allows you to add multiple values to an array in a single operation. This is particularly useful when you have an array of values that need to be appended simultaneously.

What happens if the array field does not exist in the document?

If the array field does not exist in the document, the $push operator will create a new array field and add the specified value to it. Subsequent $push operations will continue appending values to the newly created array.

Is it possible to conditionally add values to an array using the $push operator?

Yes, you can conditionally add values to an array using the $push operator in combination with other modifiers. For example, you can use the $each and $slice modifiers to add values based on certain conditions and limit the size of the array. This provides flexibility in selectively appending elements based on specific criteria.

Are there any limitations to the $push operator in MongoDB?

While the $push operator is powerful for adding elements to arrays, it's important to note that it cannot be used to update other types of fields or perform complex array transformations. For more advanced array manipulations, MongoDB provides additional update operators like $addToSet and $pull.

Conclusion

In summary, the $push operator in MongoDB allows you to add elements to an array field within a document. It appends new values to the end of the array, expanding it with additional data. The $push operator provides a convenient way to manage arrays and is useful for various use cases such as tracking user activities, managing comments, implementing notifications, and more. It can be combined with other operators like $each, $slice, and $position for advanced array updates, enabling you to add multiple values, limit array size, and control the insertion point. Understanding and utilizing the $push operator empowers you to efficiently manipulate arrays in MongoDB, enhancing the functionality and performance of your applications.

Live masterclass