Update Push Array in MongoDB
This post will show you how to add elements to an array in MongoDB using various techniques. Pushing or appending elements to an array is very convenient for quickly appending lists by adding or moving objects in an existing MongoDB document.
This course teaches how to use push operations with negative and positive integers. Negative integers provide additional push possibilities for putting data into an array.
Prerequisites:
- MongoDB must be installed and configured correctly to add elements to an array in MongoDB.
- Gain a basic understanding of the functionality of arrays.
Let’s first take a look at the table of contents of this article.
- Operators in MongoDB
- $push operator in MongoDB
- Pushing elements to an array
- Push an element to the beginning of an array
- Push elements to the end of the array
Operators in MongoDB
Operators are special symbols or keywords that tell the compiler or interpreter how to perform mathematical or logical operations. Query operators extend the functionality of MongoDB by allowing developers to write complex queries to interact with data sets relevant to their applications.
Following are the various operators in MongoDB.
- Query and Projection Operators - Query operators help discover data in the database, while projection operators change the way the data is displayed.
- Update Operators − Update operators allow you to change or add data to your database.
- Aggregation Pipeline Stages - Available aggregation stages for the aggregation pipeline.
- Aggregation Pipeline Operators − Aggregation pipeline operations have a set of operators that can be used to define and operate on documents in pipeline stages.
- Query Modifiers – Query modifiers determine how the query will be executed.
$push operator in MongoDB
In MongoDB, the $push operator is used to append values to an array. The $push operator is an update operator.
If the provided field is not in the document being changed, the $push operator creates it as a new field with the specified value as its element. If the update field is not an array type, the operation fails.
When updating, if the value is an array, the $push operator appends the entire array as a single element. Use the $push operator with the $each modifier to add each value element individually.
grammar:
db.collection.update( <query>,{ $push: { <field>: <value> } })
MongoDB $push operator example:
If you want to append 95 to the completed array field when the conditional subject is maths, we can use the following MongoDB command.
db.student.update( { "subjects" : "maths" },{ $push: { "achieve": 95 } });
Because the conditions described in the previous example match this action, the value 95 is appended to the completed array.
View the latest updated documentation:
db.student.find().pretty();
The output of the query given above can be seen in this screenshot.
MongoDB $push example when field is not an array:
If you want to add 2 to the sem column which is not an array type field, we can use the following MongoDB command.
db.student.update( { "subjects" : "maths" },{ $push: { "sem": 2 } });
Because the sem field in the above example is not an array type, the operation will fail and produce the following result.
Cannot apply $push/$push All modifier to non-array
Pushing elements to an array in MongoDB
This section describes how to use the $push operator, such as an update operation, to add elements to an array.
First, create a sample dataset containing fruits as shown below.
use fruitdb
switched to db fruitdb
db.fruit.insert({
"_id": "100",
"fruitArray": ['mango', 'banana', 'orange']
});
WriteResult({ "nInserted" : 1 })
Now verify the insertion process using the following command.
db.fruit.find({_id: "100"});
The results should resemble the following.
Now let's add another fruit to the fruitArray. In this example, execute the following command to add a 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 the pineapple has been successfully added as an element to the fruitArray.
db.fruit.find({_id: "100"}).pretty();
The output should look like this.
The result shows that the $push operator inserted the word pineapple at the end of fruitArray.
Pushing an element to the beginning of an array in MongoDB
The previous section described how to append new elements to the beginning of an array. This section will demonstrate how to insert the element grapes at the beginning of an array.
The following commands are used to do this.
db.fruit.update(
{ "_id": "100" },
{
$push: {
fruitArray: {
$each: ['grapes'],
$position: 0
}
}
}
);
Then, the following command can confirm whether the update process was successful.
db.fruit.find({_id: "100"}).pretty();
The output should be similar to the following.
The operator $position was used in the previous operation. As the name suggests, this command places an element in a user-defined array.
Also, remember that positive integers used for $position values are pushed in from the left, or beginning, of the array.
Pushing elements to the end of an array in MongoDB
The previous section demonstrated how to insert an element at the beginning of an array using a positive integer as the value of the $position operator. This section teaches you how to push items using a negative integer as the value, as shown here.
db. fruit.update(
{ "_id": "100" },
{
$push: {
fruitArray: {
$each: ['apple'],
$position: -1
}
}
});
The output should be similar to the following.
Using -1 as the value, apple is placed at the second-to-last position in the list of elements, with the last element at position 0.
Pushing multiple elements in MongoDB
This section describes how to insert, or push, multiple elements into an array.
First, in the fruit document, add another array.
db. fruit.insert({
"_id": "101",
"fruitArray": ["strawberry","guava","lemon"]
});
A new document should be generated containing the following information.
Now, add a large number of elements to the new document using the following command.
db.fruit.update(
{ "_id": "101" },
{
$push: {
fruitArray: {
$each: ['pear', 'cherry', 'lime'],
$position: -2
}
}
}
);
Since the items ['pear', 'cherry', and 'lime']
are pushed in the code above, the array can be considered as one element. This pushes or moves pear to the specified position -2, followed by cherry and lime.
It should be noted that the elements will be added to the array in the order given.
This article introduces you to various ways to add elements to an array in MongoDB. First, the lesson demonstrates how to use the $push operator to add elements to an array, such as an update operation.
It then demonstrates how to generate a sample data set, insert elements into an array, and finally test the insertion process. The article also discusses how to push elements at the beginning, middle, and end of an array and how to push multiple elements.
Remember that negative integers as values push elements to the end of the array, while positive integers push elements in from the left or beginning of the array.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
$ne operator in MongoDB
Publish Date:2025/04/11 Views:84 Category:MongoDB
-
This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val
MongoDB $Set Operator
Publish Date:2025/04/11 Views:159 Category:MongoDB
-
With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given
Difference between $push and $addToSet in MongoDB
Publish Date:2025/04/11 Views:63 Category:MongoDB
-
This article explains the operators in MongoDB. What is the purpose of $push and $addToSet operators. Furthermore, the difference between these two operators is given in the code snippet. This article discusses the following topics. Operato
Sort a collection by date in MongoDB
Publish Date:2025/04/11 Views:64 Category:MongoDB
-
In this MongoDB tutorial, the problem of sorting a collection in MongoDB is discussed. The different ways to sort a collection in the database are briefly explained. Using sort() function in MongoDB This problem is solved using the MongoDB
Counting records in MongoDB
Publish Date:2025/04/11 Views:146 Category:MongoDB
-
This article discusses operators in MongoDB, aggregation operators, and different ways to calculate the total number of records. Operations in MongoDB CRUD operations are a user interface concept that allows users to browse, search, and cha
Pretty printing in MongoDB
Publish Date:2025/04/11 Views:150 Category:MongoDB
-
This article will discuss how to use pretty printing in MongoDB to display formatted results. Pretty printing in MongoDB A cursor is an object that allows programmers in the Mongo world to iterate over documents in a Mongo collection. Altho
MongoDB Adding Elements to an Array
Publish Date:2025/04/11 Views:136 Category:MongoDB
-
This article will cover the various ways to add to an array in MongoDB. Adding to an array in MongoDB Use the $push operator to add values to an array The $push operator is one of the various array update operators provided by MongoDB
MongoDB Search by ID
Publish Date:2025/04/11 Views:131 Category:MongoDB
-
The following article provides an overview of MongoDB find by Id() method. MongoDB provides a find by Id() function which can retrieve documents matching a user id. To use search by Id() in MongoDB, you need to use the find() function. If n
MongoDB starts with a query
Publish Date:2025/04/10 Views:195 Category:MongoDB
-
In this MongoDB article, users will learn how to start queries using $regex. It provides regular expression functionality for pattern matching strings in queries. MongoDB starts querying using $regex If you want to use $regex , use one of t