MongoDB Adding Elements to an Array
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 and is used to update the contents of an array field in a document. The $push operator can add a specific value to an array.
The $push operator adds an item to the end of an array. This operation fails if the field specified by the $push operator is not an array.
grammar:
{
$push: {
<field1>: <value1>,
<field2>: <value2>,
...
}
}
In this case, you can use arrays, embedded/nested documents, or dot notation to specify the fields. Depending on your needs, you can use this operator in conjunction with methods like update(), findAndModify(), etc.
If the provided field is not present in the document, the $push operator will add the array field with the value as its element.
If the value of the $push operator is an array, the entire array will be added as a single element. Alternatively, if you wish to add each value component independently, you can use the $each modifier with the $push operator.
Consider the following example to help you better understand the previous idea.
db.employees.update(
{name: "John Doe"},
{$push: {'professional_skills.$.technical': { skill: "C++", exp: '1' }}}
)
In the above example, we are changing the user "John Doe" in the employees collection. The professional_skills array contains technical skills, communication skills, etc., which is what we store here.
We transform the new technical expertise of employees into technical skills by integrating their experience as objects. Run the above line of code in a MongoShell that is compatible with MongoDB.
Output:
{
"_id" : ObjectId("54f612b6029b47919a90cesd"),
"email" : "johndoe@exampledomain.com",
"name" : "John Doe",
"country" : "USA",
professional_skills: [
{
technical:[
{ skill:'javascript', exp: 4},
{ skill:'c', exp: 3}
]
},
]
}
Use the $addToSet operator to add values to an array
When adding a value to an array, the $addToSet operator checks if the value already exists in the array; otherwise, it does nothing. This operator does not add duplicates to the array, nor does it affect duplicates that already exist.
In this case, the order of the values does not matter.
grammar:
{
$addToSet: {
<field1>: <value1>,
<field2>: <value2>,
...
}
}
In this case, you can use arrays, embedded/nested documents, or dot notation to specify the fields. Depending on your needs, you can use this operator in conjunction with methods like update(), findAndModify(), etc.
Fields other than arrays cannot be used with this operator. If the requested field does not exist, the $addToSet operator generates an array field in the document containing the value or item.
Consider the following example to help you better understand the previous idea.
db.employees.update(
{name: "John Doe"},
{$addToSet: {'professional_skills.$.technical': { skill: "C++", exp: '1' }}}
)
In the above example, we are changing the user "John Doe" in the employees collection. The professional_skills array contains technical skills, communication skills, etc., which is what we store here.
We transform the new technical expertise of employees into technical skills by integrating their experience as an object. The main difference between them is that $addToSet will add the element if it does not exist, while $push will append the new element to an array or list.
Run the above code in a MongoShell that is compatible with MongoDB.
Output:
{
"_id" : ObjectId("54f612b6029b47919a90cesd"),
"email" : "johndoe@exampledomain.com",
"name" : "John Doe",
"country" : "USA",
professional_skills: [
{
technical:[
{ skill:'javascript', exp: 4},
{ skill:'c', exp: 3}
]
},
]
}
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 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
Export all collections in MongoDB
Publish Date:2025/04/10 Views:188 Category:MongoDB
-
This MongoDB tutorial will show you how to export all MongoDB collections. Most databases and language frameworks allow you to export data. This makes the data useful to other programs, applications, or languages in various forms. CSV