JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Difference between $push and $addToSet in MongoDB

Author:JIYIK Last Updated:2025/04/11 Views:

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.

  1. Operators in MongoDB
  2. $push in MongoDB
  3. $addToSet in MongoDB

Operators in MongoDB

Operators are special symbols or keywords that tell the compiler or interpreter to perform mathematical or logical operations.

Query operators enhance the functionality of MongoDB by allowing developers to create complex queries to interact with data sets that match their applications.

Different types of operators in MongoDB are explained below.

  1. Query and Projection Operators - Query operators help discover data in the database, while projection operators change the way the data is displayed.
  2. Update Operators − Update operators allow you to change or add data to your database.
  3. Aggregation Pipeline Stages - Available aggregation stages for the aggregation pipeline.
  4. Aggregation Pipeline Operators − Aggregation pipeline operations have a set of operators that can be used to define and operate on documents in pipeline stages.
  5. Query Modifiers – Query modifiers determine how the query will be executed.

$push operator in MongoDB

The $push operator in MongoDB is used to append the given value to an array. The $push operator is an update operator.

If the specified field does not exist in the document to be updated, the $push operator adds it as a new field with the specified value as its element. If the update field is not an array type, the operation fails.

If the value is an array, the $push operator appends the entire array as a single element when updating. If you want to add each value element individually, use the $push operator with the $each modifier.

grammar:

db.collection.update( <query>,{ $push: { <field>: <value> } })

The following database collection will be used in all examples.

Simple collection:

db={
  "student": [
    {
      "_id": 1,
      "sem": 1,
      "subjects": [
        "phys",
        "chem",
        "maths",
        "gkn",
        "stat",
        "astro"
      ],
      "achieve": [
        70,
        87,
        90,
        90,
        65,
        81
      ]
    }
  ]
}

MongoDB $push Operator Example

If we want to append 95 to the array field completed when the conditional subject is “maths”, we can use the following MongoDB command.

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

Because the condition described in the previous example matches 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.

push operator mongodb

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

MongoDB $push example using $each modifier

If we want to append many entries or multiple elements (77, 49, 83) to the array completed for the record student with the condition subject being “Mathematics”, we can use the following MongoDB command.

db.student.update( { "subjects" : "maths" },{ $push: { "achieve": {$each : [77,49,83 ]} } });

The $each modifier is used in the example above to append multiple entries 77, 49, 83 to an array completion matching the standard subject "maths".

View the latest updated documentation:

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

The output of the query given above can be seen in this screenshot.

push operator with each


$addToSet in MongoDB

$addToSetThe operator adds or appends a value to an array only if the value does not already exist in the array. When the value is already in the array, $addToSet returns the same array without changing it.

$addToSetoperator ensures that there are no duplicate entries in the array when updating; however, the order of elements in the display can be modified after the values ​​have been added.

grammar:

db.collection.update( { <field>: <value> }, { $addToSet: { <field>: <addition> } } );

The collection used above:

 { "_id" : 1, "sem" : 1, "achieve" : [  80,  70,  90 ] }

$addToSet Example of appending a value

If we want to append the value 92 to the array, we can use the following MongoDB command.

db.student.update( { "sem": 1}, { $addToSet: { "achieve": 92 } } );

The preceding code appends 92 to the array field completion.

View the latest updated documentation:

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

Output of the command:

{ "_id" : 1, "achieve" : [ 70, 80, 90, 92 ], "sem" : 1 }

$addToSet Example of adding multiple values ​​using the $each modifier

The following MongoDB command can be completed to append the numbers 10 and 11 to the array field.

db.student.update( { "sem": 1}, { $addToSet: { "achieve":{$each:[10,11]}}});

In the above example, the numbers 10 and 11 are appended to the array field implemented using the $each modifier.

View the latest updated documentation:

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

The output of the query given above can be seen in this screenshot.

addToSet Operator

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.

Article URL:

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

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

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

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial