JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

MongoDB $Set Operator

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

With the help of this article, you will learn how to use $setthe 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 value. $setThe operator expression uses the following syntax.

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

You would specify one in an embedded document or array using dot notation <field>.


MongoDB $set Operator

If the field does not exist, $setthe operator creates a field with the specified value as long as the new field does not violate any constraints.

For example, if you provide a dotted path to a field that does not exist, $setthe operator will generate embedded documents as needed to complete the dotted path.

Additionally, if you specify multiple field-value pairs, the $set operator updates or creates each field.

You can create the following product collections.

db={
  "products": [
    {
      _id: 100,
      quantity: 250,
      instock: true,
      reorder: false,
      details: {
        model: "PTI",
        make: "Breakout"
      },
      tags: [
        "jeans",
        "clothing"
      ],
      ratings: [
        {
          by: "CustomerIK",
          rating: 3
        }
      ]
    }
  ]
}

Setting the Top-Level Field

_idThe following operation uses the $set operator to update the values ​​of the details field, quantity field, and tags field for documents matching the condition equal to 100. The query for this is given below.

db.products.update(
   { _id: 100 },
   { $set:
      {
        quantity: 500,
        details: { model: "2600", make: "Outfitters" },
        tags: [ "coats", "outerwear", "clothing" ]
      }
   }
)

The above operation updates the content below.

  1. The quantity value is 500.
  2. Details field with new embedded document
  3. Mark the fields with the new array

The results of the above query are shown in the screenshot below.

Set Top-Level Fields


Setting fields in embedded documents

You would use dot notation to specify in an embedded document or array <field>. _idThe following operation updates the make field in the detail document for documents matching the condition equal to 100.

The query for this is given below.

db.products.update(
   { _id: 100 },
   { $set: { "details.make": "Breakout Kids" } }
)

The results of the above query are shown in the screenshot below.

Setting fields in embedded documents


Setting an element in an array

The following operation modifies the value in the second element of the tags field (array index 1) and the ratings field in the first element of the ratings array (array index 0) for documents that satisfy the condition _id equals 100.

The query for this is given below.

db.products.update(
   { _id: 100 },
   { $set:
      {
        "tags.1": "wind breaker",
        "ratings.0.rating": 2
      }
   }
)

The results of the above query are shown in the screenshot below.

Setting an element in an array


$set (aggregation)

$set (aggregation) adds new fields to a document. $set outputs a document containing all existing fields from the input document plus the newly added fields.

$set(aggregate) has the following syntax.

{ $set: { <newField>: <expression>, ... } }

$set is a command that adds new fields to an existing document. Users can include one or more $set stages in an aggregation operation.

Use dot notation to add a field or fields to an embedded document (including documents in an array). Use $concatArraysto add elements to an existing array field using $set.


Using two $set stages

Create a sample grades collection using the following content.

db={
  "grades": [
    {
      _id: 1,
      student: "Ali",
      homework: [10, 8, 9],
      quiz: [9, 8],
      extraCredit: 3
    },
    {
      _id: 2,
      student: "Manahil",
      homework: [3, 8, 5],
      quiz: [7, 9],
      extraCredit: 6
    }
  ]
}

In the following process $setthree new fields are added to the output document using two stages. The query for this is given below.

db.grades.aggregate( [
   {
     $set: {
        totalHomework: { $sum: "$homework" },
        totalQuiz: { $sum: "$quiz" }
     }
   },
   {
     $set: {
        totalScore: { $add: [ "$totalHomework", "$totalQuiz", "$extraCredit" ] } }
   }
] )

The operation returns the following document as shown in the following screenshot.

Use two setup stages


Adding fields to embedded documents

Create a sample collection transport with the following content.

db={
  "transport": [
    {
      _id: 1,
      type: "sedan",
      specs: { doors: 4, wheels: 4}
    },
    {
      _id: 2,
      type: "motorbike",
      specs: {doors: 0, wheels: 2}
    },
    {
      _id: 3,
      type: "jet ski"
    }
  ]
}

The following aggregation operation creates a new field fuel_type in the embedded document specification. The query for this is given below.

db.transport.aggregate( [
   { $set: { "specs.fuel_type": "super" } }
] )

The operation returns the following results, as shown in the following screenshot.

Adding fields to embedded documents


Overwrite existing fields

When a $set operation specifies an existing field name, the original field is replaced. Use the following items to make a sample set of pets.

db={
  "pets": [
    {
      _id: 1,
      dogs: 10,
      cats: 5
    }
  ]
}

The subsequent $set operation overwrites the cats field. The query for this is given below.

db.pets.aggregate( [
  { $set: { "cats": 20 } }
] )

The operation returns the following document as shown in the following screenshot.

Overwrite existing fields


Adding elements to an array

Create a sample grades collection using the following records.

db={
  "grades": [
    {
      _id: 1,
      student: "Ali",
      homework: [10, 8, 9],
      quiz: [9, 8],
      extraCredit: 3
    },
    {
      _id: 2,
      student: "Manahil",
      homework: [3, 8, 5],
      quiz: [7, 9],
      extraCredit: 6
    }
  ]
}

Users can use the $set operator with the $concatArrays expression. This will add an element to an existing array field.

The following operation uses $set to replace the homework field with a new array whose elements are the concatenation of the current homework array and another array containing the new grades [7]. The query for this is given below.

db.grades.aggregate([
   { $match: { _id: 2 } },
   { $set: { homework: { $concatArrays: [ "$homework", [ 7 ] ] } } }
])

The operation returns the following document as shown in the following screenshot.

Adding elements to an array

In this article, you learned how to use the $set operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object.

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

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

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