-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
inc.txt
61 lines (44 loc) · 2.03 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
====
$inc
====
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
.. update:: $inc
The :update:`$inc` operator increments a value of a field by a
specified amount. If the field does not exist, :update:`$inc` adds
the field and sets the field to the specified amount.
:update:`$inc` accepts positive and negative incremental
amounts. Consider the following syntax:
.. code-block:: javascript
{ $inc: { <field1>: <amount1>, ... } }
The following example increments the value of ``quantity`` by ``5``
for the *first* matching document in the ``products`` collection
where ``sku`` equals ``abc123``:
.. code-block:: javascript
db.products.update( { sku: "abc123" },
{ $inc: { quantity: 5 } } )
To update all matching documents in the collection, specify
``multi:true`` option in the :method:`~db.collection.update()`
method. For example:
.. code-block:: javascript
db.records.update( { age: 20 }, { $inc: { age: 1 } }, { multi: true } );
The :method:`~db.collection.update()` operation increments the value
of the ``age`` field by ``1`` for all documents in the ``records``
collection that have an ``age`` field equal to ``20``.
The :update:`$inc` operator can operate on multiple fields in a
document. The following :method:`~db.collection.update()` operation
uses the :update:`$inc` operator to modify both the ``quantity``
field and the ``sales`` field for the *first* matching document in
the ``products`` collection where ``sku`` equals ``abc123``:
.. code-block:: javascript
db.products.update( { sku: "abc123" },
{ $inc: { quantity: -2, sales: 2 } } )
In the above example, the :update:`$inc` operator expression
specifies ``-2`` for the ``quantity`` field to *decrease* the value
of the ``quantity`` field (i.e. increment by ``-2``) and specifies
``2`` for the ``sales`` field to increase the value of the ``sales``
field by ``2``.