The Wayback Machine - https://web.archive.org/web/20241122204730/https://www.geeksforgeeks.org/mongodb-push-operator/
Open In App

MongoDB $push Operator

Last Updated : 10 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The $push operator in MongoDB is a powerful tool used to update arrays within documents. It appends the entire array as a single element. To add each element of the array individually, the $each modifier can be used alongside $push. In this article, We will learn about the MongoDB $push Operator by understanding various examples in detail.

$push Operator in MongoDB

  • The $push operator in MongoDB is used to update the array in MongoDB. It inserts a new value into the array in the specific index.
  • If the mentioned field is absent in the document to update, the $push operator adds it as a new field and includes the mentioned value as its element.
  • If the value is an array, the $push operator appends the whole array as a single element.
  • To add each element of the value separately, the $push operator can be used with the $each modifier.

To learn how to efficiently manage arrays and embedded documents in full-stack applications, the Full Stack Development with Node JS course covers advanced usage of MongoDB operators like $push

Syntax:

The syntax for using the $push operator is:

{ $push: { <field1>: <value1>, ... } }

Here, <field> can specify with dot notation in embedded/nested documents or an array.

We can also use the modifiers with the $push operator:

Syntax:

{ $push: { <field1>: { <modifier1>: <value1>, ... }, ... } }

The processing of the push operation with modifiers works in the following order:

  • First update the array to add items in the correct position.
  • Second, apply sort if specified.
  • Third slice the array if specified.
  • Fourth store the array.

Note:

Here the order in which the modifiers appear in the $push operator does not matter.

List of $push operator modifiers

Below are the modifiers in MongoDB that can be used with $push operator.

Modifier Description
$each It is used to append multiple values to the array field.
$slice It is used to limit the number of array items and require the use of the $each modifier.
$sort It is used to order items of the array and require the use of the $each modifier.
$position It is used to specify the location in the array at which to insert the new items and require the use of the $each modifier. If the $push operator does not use $position modifier, then this operator will append the items to the end of the array.

Examples of MongoDB $push Operator

In the following examples, we are working with

Database: GeeksforGeeks
Collection: contributor
Document: two documents that contain the details of the contributor in the form of field-value pairs

Output:

demo database and collection creation

Example 1: Append a 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”).

Query:

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

Output:

appending a single value to an array example using $push operator output

Example 2: Append 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”).

Query:

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

Output:

appending multiple values to an array using $push operator

Example 3: Append Multiple Values to 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.

Query:

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

Output:

appending multiple values to an array in the nested/embedded document using $push operator

Example 4: Use $push Operator with Multiple Modifiers

In this example, we are using multiple modifiers like $each, $sort, and $slice with $push operator.

Query:

db.contributor.update({name: &quot;Rohit&quot;},
{$push: { language: { $each: [&quot;C&quot;, &quot;Go&quot;],
$sort: 1, $slice: 4}}})

Output:

modifiers with $push operator example output

Here,

  • The $each modifier is used to add multiple documents to the language array.
  • The $sort modifier is used to sort all the items of the modified language array in ascending.
  • The $slice modifier is used to keep only the first four sorted items of the language array.

KeyTakeAways About MongoDB $push Operator

  • The $push operator in MongoDB is used append a new value into the array in the specific index.
  • If the specified field in the $push operator is not present in the document, then this operator will add the array field with the value as its items.
  • You can use this operator with methods like update(), findAndModify(), etc. according to your requirements.
  • The $push operator inserts items at the end of the array.
  • If the specified field in the $push operator is not an array, then this operation will fail.
  • If the value of the $push the operator is an array, then this operator will append the whole array as a single element. And if you want to add each item of the value separately, then you can use $each modifier with $push the operator.

Conclusion

The $push operator in MongoDB is essential for manipulating arrays within documents. It provides flexibility by allowing single or multiple values to be appended to an array, and by supporting various modifiers for more complex operations. Understanding and using the $push operator effectively can greatly enhance your data management capabilities in MongoDB.

FAQs on MongoDB $push

1. What happens if the field specified in the $push operator does not exist in the document?

If the specified field does not exist, the $push operator creates the field and adds the specified value as its element.

2. Can the $push operator append an entire array as a single element?

Yes, if the value specified in the $push operator is an array, it appends the entire array as a single element. To add each element of the array individually, use the $each modifier.

3. How can the $each modifier be used with the $push operator?**

The $each modifier allows you to append multiple values to an array field. It is particularly useful when you want to add multiple elements to an array in a single operation.

4. What are the other modifiers that can be used with the $push operator?

Other modifiers include $slice, $sort, and $position. These modifiers allow you to limit the number of array items, order items in the array, and specify the position to insert new items, respectively



Previous Article
Next Article

Similar Reads

How to push data in a MongoDB document ?
The insertOne() and insertMany() are the two methods of the MongoDB module in node.js that are used to push the documents in the collections of the MongoDB database. The insertOne() method inserts one data at a time into the collection and insertMany() method inserts multiple data into the collection of the MongoDB database. In this article, we wil
2 min read
Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
How to Integrate MongoDB Atlas and Segment using MongoDB Stitch
Data integration has become a crucial component of modern business strategies, allowing companies to enhance the power of data for informed decision-making. According to a recent survey, 85% of businesses believe that integrating data across multiple platforms is important for their success. In this article, We will learn about What is MongoDB Stit
5 min read
MongoDB - Delete Multiple Documents Using MongoDB Shell
The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter. The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method
2 min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. You might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. This guide explains how to connect MongoDB Atlas Cluster to MongoDB Compass. The connection process involves obtaining a connection string from MongoDB Atlas, configuring MongoDB
4 min read
MongoDB Shell vs MongoDB Node.JS Driver
MongoDB Shell and the MongoDB Node.js Driver are both tools for interacting with MongoDB, but they serve different purposes and are used in different contexts. Here's a comparison of the two: MongoDB Node.JS DriverA Node.js package called the MongoDB Node.js Driver enables programmatic communication between applications and MongoDB databases. Throu
4 min read
MongoDB Compass vs MongoDB Atlas
MongoDB is a popular NoSQL database known for flexibility and scalability. MongoDB Compass offers a graphical interface for managing databases visually while MongoDB Atlas is a cloud-based service for automated management and scaling of MongoDB databases. In this article, We will learn about the in-depth understanding of the difference between the
5 min read
MongoDB AND operator ( $and )
MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array. You can use this operator in methods like find(), update(), etc. ac
2 min read
MongoDB NOT operator ( $not )
MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression. It also includes those documents that don't contain the field. You can
2 min read
MongoDB OR operator ( $or )
MongoDB provides different types of logical query operators and $or operator is one of them. This operator is used to perform logical OR operation on the array of two or more expressions and select or retrieve only those documents that match at least one of the given expression in the array. You can use this operator in methods like find(), update(
2 min read
MongoDB NOR operator ( $nor )
MongoDB provides different types of logical query operators and $nor operator is one of them. This operator is used to perform logical NOR operation on the array of one or more expressions and select or retrieve only those documents that do not match all the given expression in the array. You can use this operator in methods like find(), update(),
2 min read
MongoDB $sqrt Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages $sqrt operator is one of them. This operator is used to find the square root of a positive number and returns the result as a double. Syntax: { $sqrt: <number> } Here, the number is a valid expression until it resolves to a non
2 min read
MongoDB $mod Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and $mod operator is one of them. This operator is used to divide one number by another number and return the remainder. Syntax: { $mod: [ <expression1>, <expression2> ] } Here, in this operator, the arguments passed in a
1 min read
MongoDB - $ne Operator
MongoDB $ne or "not equals" operator is one of the comparison operators. The $ne operator selects those documents where the field value is not equal to the given value. It also includes those documents that do not contain the specified field. You can use this operator in methods like find(), update(), etc. as per your requirement. Syntax{field: {$n
2 min read
MongoDB - $nin Operator
MongoDB $nin or " not in" is one of the comparison query operators. The $nin operator selects those documents where the field value is not equal to any of the given values in the array and the field that does not exist. You can use this operator in methods like find(), update(), etc. according to your requirements. Syntax{field: {$nin: [value1, val
2 min read
MongoDB - $max Operator
MongoDB $max or maximum operator is one of the field update operators. $max operator updates the field with the specified value if the specified value is greater than the current value. Important Points This operator will compare the values of different data types according to the BSON comparison order.You can also use this operator in embedded/nes
3 min read
MongoDB - $min operator
MongoDB $min or minimum operator is one of the field update operators. $min operator updates the field with the specified value if the specified value is less than the current value. The $min operator will compare the values of different data types according to the BSON comparison order. This operator can also be used in embedded/nested documents u
3 min read
MongoDB - $inc Operator
MongoDB $inc or increment operator is a type of field update operator. $inc operator increases the values of the fields to the specified amount or increases the field by the given value. Important PointsThis operator accepts positive and negative values.If the given field does not exist, then this operator will create a field and set the value of t
2 min read
MongoDB - $lt Operator
MongoDB $lt operator or less than operator is one of the comparison operators. The $lt operator selects the documents with a value less than (<) the given value. You can use this operator in methods like, find(), update(), etc. as per your requirements. Syntax{field: {$lt: value}}MongoDB $lt Operator ExampleIn the following examples, we are work
2 min read
MongoDB - $lte Operator
MongoDB $lte Operator is one of the comparison operators. $lte operator selects those documents where the field value is less than equal to (<=) the given value. This operator can be used in methods like find(), update(), etc. according to your requirements.. Syntax{field: {$lte: value}}MongoDB $lte Operator ExampleIn the following examples, we
2 min read
How to use the $lookup operator in aggregation pipelines in MongoDB?
One of the essential stages of the Aggregation Pipeline is the $lookup. It enables us to accomplish a left outer join between two collections. This step is quite beneficial when we have to compose data from different collections into a single document. The Aggregation Pipeline in MongoDB is a robust tool that allows us to manipulate and analyze dat
4 min read
MongoDB $gt Operator
MongoDB $gt operator selects documents where the value of a field is greater than a specified value. $gt Operator in MongoDBThe $gt operator in MongoDB is a comparison operator. It is used to find documents where the value in the field is greater than(>) a given value. This operator can be used with other methods like find, update, etc. accordin
2 min read
MongoDB - Rename Operator ($rename)
MongoDB $rename operator is a powerful tool for updating field names within documents which ensures data consistency and structure. This operator allows developers to rename fields in a MongoDB collection, including those nested within documents or arrays. In this article, We will learn about the MongoDB $rename by understanding various examples in
4 min read
MongoDB $arrayElemAt Operator
MongoDB $arrayElemAt operator is a key component of the aggregation framework, allowing users to retrieve specific elements from arrays within their documents. In this article, We will learn about the MongoDB $arrayElemAt by understanding various examples in detail and so on. MongoDB $arrayElemAtMongoDB provides different types of array expression
3 min read
MongoDB - $setOnInsert Operator
The $setOnInsert operator in MongoDB is a powerful tool used in updating operations with the upsert option. It allows us to specify values that should be set only when a new document is inserted. In this article, we will learn about the $setOnInsert Operator in MongoDB in detail and so on. MongoDB $setOnInsert OperatorMongoDB $setOnInsert Operator
4 min read
MongoDB - Positional Operator ($)
MongoDB provides a variety of array update operators to modify the values within array fields in documents. One such operator is the positional operator $. This operator allows us to update an element in an array without explicitly specifying the position of that element. In this article, We will learn about the Positional Operator($) in MongoDB in
4 min read
MongoDB $multiply Operator
In MongoDB, the $multiply operator is a powerful tool used in aggregation pipelines to perform multiplication operations. This operator takes one or more expressions as arguments and multiplies them to produce a result. In this article, We will learn about the MongoDB $multiply Operator in detail. MongoDB $multiply OperatorMongoDB provides differen
3 min read
MongoDB $size Operator
MongoDB $size operator is an important tool for calculating the total number of elements within an array. This operator plays a crucial role in MongoDB's aggregation pipeline stages, particularly for tasks requiring the analysis and manipulation of array data. In this article, We will learn about the MongoDB $size Operator by understanding various
3 min read
MongoDB $abs operator
The $abs operator in MongoDB is a fundamental arithmetic expression operator used in aggregation pipeline stages. Its primary function is to calculate the absolute value of a specified number. In this article, We will learn about the MongoDB $abs operator by understanding various examples in detail. MongoDB $abs operatorMongoDB provides different t
3 min read
MongoDB $add Operator
The $add operator in MongoDB is a versatile arithmetic expression operator used to add numbers together or concatenate numbers and dates in the aggregation pipeline. This operator plays an important role in data manipulation and transformation. In this article, We will learn about the MongoDB $add Operator by understanding various examples in detai
3 min read
three90RightbarBannerImg