$push Operator in MongoDB

Learn via video courses
Topics Covered

Overview

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.

Syntax of $push in MongoDB

The syntax of the $push operator in MongoDB is,

  • The collection is the name of the collection.
  • The <query> parameter is used to get the documents to be updated.
  • The <field> represents the array field to which we want to add elements. We can specify multiple fields in a single query.
  • The <value> can be a single value or an array of values that need to be appended to the array specified by the field.

In the aggregation pipeline, the $push in mongodb can be used in four stages such as $bucket, $bucketAuto, $group, and $setWindowFields. An example of this is provided in the examples section.

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,

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

  • The $each modifier allows appending multiple values to an array field. It accepts an array of values as input.
  • The $sort modifier performs sorting operations in ascending or descending order as specified. This operator can only be used with the $each modifier.
  • 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.
  • 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.
  • 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.

Examples of $push Operator in MongoDB

Let's explore a few examples to understand how the $push in mongoDB works. Consider the following users document,

We will modify the above document in the upcoming examples.

Appending Single Value to an Array

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

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,

Appending Multiple Values to an Array

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

After executing the above query, the modified document is,

How to Use Modifiers with $push?

Modifiers like $slice, $position, and $sort can be used to further modify the array.

For example, to get only the last four elements of the favorites array, we can use the $slice modifier,

  • The negative value in the slice modifier slices the array from the end of the array
  • If you provide a positive value for $slice, it limits the array to include only the specified number of elements starting from the beginning of the array.
  • The slice operation is performed after pushing the new elements to the array.

The document after using the operator, push in MongoDB is,

We can also use the $position modifier to insert a new favorite fruit, apple, at the second position in the favorites array. The following query illustrates this,

  • The specified index is zero-based and the specified index can also be negative. Negative values represent the index offset from the end of the array.
  • If the specified index is greater than the array's length, the new elements will be appended at the end of the array.

After executing this operator, push in mongoDB, the document will be updated as follows,

Suppose we want to add a new favorite fruit, a banana, into the favorites array while ensuring that the array remains sorted in ascending order. We can achieve this using the $push in mongoDB with the $each and $sort modifiers. The following query shows this,

  • For the sort modifier, if a value of 1 is provided, the elements are sorted in ascending order and the elements in descending order for the value of -1. The default value is 1.
  • The $sort operator considers the existing elements within the array as well as the newly pushed elements.

After executing the query, the values in the favorites array are sorted in lexicographical order, and the document will be updated as follows,

If we want to make sure that no duplicate values are added to the array, we can use the $addToSet modifier. The following example query demonstrates the $addToSet operator,

The addToSet modifier takes a boolean value. The default value is false, and when set to true, it prevents adding duplicates to the array. The resulting document after performing the above query is:

The $push in MongoDB can also be used as part of the $group stage of the aggregation pipeline to perform more complex operations. Let us consider the following collection with three documents,

Let us perform a query which to group the documents based on the favorites fruit array and keep only the first two fruits in the favorites array for each group. The following query can be used to achieve this,

  • In the above query, the $group stage groups the documents by the name field.
  • The $push modifier is used to create an array of grouped documents with a favorites array.
  • The $each modifier with an empty array [] within $push is used to indicate that we want to push each element of the array individually.
  • The $slice modifier limits the resulting array to only the first two elements.

After performing the query, the resulting document will be,

In the output, the _id field represents the distinct users in the group and the favorites field contains an array with the first two elements from the original favorites array.

FAQs

Q: Can $push in mongoDB be used with nested arrays?

A: Yes, the $push operator can be used with nested arrays. You can specify the path to the nested array in the update operation.

Q: What does the $push in MongoDB do if the specified field doesn't exist?

A: If the specified field does not exist in the document, the $push operator will create a new array field and append the specified value to it.

Q: Can we use operator push in MongoDB with an array of objects?

A: Yes, you can use $push to append objects to an array field. You should also ensure that the objects contain a valid JSON structure.

Conclusion

  • The operator, $push in MongoDB provides a powerful mechanism to append elements to an array field within a document.
  • The $push operator makes efficient and atomic updates while also ensuring data integrity.
  • Mongodb provides various modifiers like $each, $slice, $sort, $addToSet, and $position to customize the behavior of the push operation.
  • The operator, push in MongoDB can also be used in four stages of the aggregation pipeline.
  • We can use the push in MongoDB to perform push operations in various types of arrays, like nested arrays and arrays of objects.