MongoDB - Оператор приращения ($ inc)

Опубликовано: 2 Марта, 2022

MongoDB provides different types of field update operators to update the values of the fields of the documents and $inc operator is one of them. This operator is used to increase the values of the fields to the specified amount or to increase the field by the given value.

Вы также можете использовать этот оператор во встроенных / вложенных документах. Вы можете использовать этот оператор в таких методах, как update (), updateOne () и т. Д. В соответствии с вашими требованиями.

  • Этот оператор принимает положительные и отрицательные значения.
  • Если данное поле не существует, то этот оператор создаст поле и установит значение этого поля.
  • Этот оператор сгенерирует ошибку, если вы используете этот оператор с полем нулевого значения.
  • Это атомарная операция в одном документе.

Синтаксис:

 {$ inc: {field1: amount1, field2: amount2, ...}}

В следующих примерах мы работаем с:

Database: GeeksforGeeks
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.

Увеличьте значение поля с помощью оператора $ inc:

In this example, we are updating the fields of an employee’s document whose name is Mohit by incrementing the value of publish articles field to 10 and decreasing the value of the salary field to -100.

db.contributor.update({name: "Mohit"}, {$inc: {publisharticles: 10, salary: -100}})

Увеличьте значение поля в массиве с помощью оператора $ inc:

In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a field to 10.

db.contributor.update({name: "Priya", "points._id": "g_1"}, {$inc: {"points.$.a":10}})

Увеличьте значение поля во встроенном документе с помощью оператора $ inc:

In this example, we are updating the field of an employee’s document whose name is Mohit by incrementing the value of a rank to 2.

db.contributor.update({name: "Amu"}, {$inc: {"personal.rank": 2}})