/
inc.txt
107 lines (70 loc) · 2.13 KB
/
inc.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
====
$inc
====
.. default-domain:: mongodb
.. facet::
:name: programming_language
:values: shell
.. meta::
:description: Use the $inc operator to increment field values by specified amounts. $inc creates fields if absent, errors on null values, and is atomic within a document.
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. update:: $inc
The :update:`$inc` operator increments a field by a specified value.
Compatibility
-------------
.. |operator-method| replace:: ``$inc``
.. include:: /includes/fact-compatibility.rst
Syntax
------
The :update:`$inc` operator has the following form:
.. code-block:: javascript
{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
.. include:: /includes/use-dot-notation.rst
Behavior
--------
.. include:: /includes/fact-update-operator-processing-order.rst
The :update:`$inc` operator accepts positive and negative values.
If the field does not exist, :update:`$inc` creates the field and sets
the field to the specified value.
Use of the :update:`$inc` operator on a field with a null value will
generate an error.
:update:`$inc` is an atomic operation within a single document.
.. include:: /includes/extracts/update-operation-empty-operand-expressions-inc.rst
Example
-------
Create the ``products`` collection:
.. code-block:: javascript
db.products.insertOne(
{
_id: 1,
sku: "abc123",
quantity: 10,
metrics: { orders: 2, ratings: 3.5 }
}
)
The following :method:`~db.collection.updateOne()` operation uses the
:update:`$inc` operator to:
- increase the ``"metrics.orders"`` field by 1
- increase the ``quantity`` field by -2 (which decreases ``quantity``)
.. code-block:: javascript
db.products.updateOne(
{ sku: "abc123" },
{ $inc: { quantity: -2, "metrics.orders": 1 } }
)
The updated document would resemble:
.. code-block:: javascript
{
_id: 1,
sku: 'abc123',
quantity: 8,
metrics: { orders: 3, ratings: 3.5 }
}
.. seealso::
- :method:`db.collection.updateMany()`
- :method:`db.collection.findAndModify()`