|
6 | 6 |
|
7 | 7 | .. operator:: $inc
|
8 | 8 |
|
9 |
| - The :operator:`$inc` operator increments a value by a specified |
10 |
| - amount if field is present in the document. If the field does not |
11 |
| - exist, :operator:`$inc` sets field to the number value. For |
12 |
| - example: |
| 9 | + The :operator:`$inc` operator increments a value of a field by a |
| 10 | + specified amount. If the field does not exist, :operator:`$inc` sets |
| 11 | + the field to the specified amount. :operator:`$inc` accepts positive |
| 12 | + and negative incremental amounts. |
| 13 | + |
| 14 | + The following example increments the value of ``field1`` by the |
| 15 | + value of ``amount`` for the *first* matching document in the |
| 16 | + collection where ``field`` equals ``value``: |
13 | 17 |
|
14 | 18 | .. code-block:: javascript
|
15 | 19 |
|
16 |
| - db.collection.update( { field: value }, { $inc: { field1: amount } } ); |
| 20 | + db.collection.update( { field: value }, |
| 21 | + { $inc: { field1: amount } } ); |
17 | 22 |
|
18 |
| - In this example, for documents in ``collection`` where |
19 |
| - ``field`` has the value ``value``, the value of ``field1`` |
20 |
| - increments by the value of ``amount``. The above operation only |
21 |
| - increments the *first* matching document *unless* you specify |
22 |
| - multi-update: |
| 23 | + To update all matching documents in the collection, specify |
| 24 | + ``multi:true`` in the :method:`~db.collection.update()` method: |
23 | 25 |
|
24 | 26 | .. code-block:: javascript
|
25 | 27 |
|
26 |
| - db.collection.update( { age: 20 }, { $inc: { age: 1 } } ); |
27 |
| - db.collection.update( { name: "John" }, { $inc: { age: 1 } } ); |
28 |
| - |
29 |
| - In the first example all documents that have an ``age`` field with |
30 |
| - the value of ``20``, the operation increases ``age`` field by |
31 |
| - one. In the second example, in all documents where the ``name`` |
32 |
| - field has a value of ``John`` the operation increases the value |
33 |
| - of the ``age`` field by one. |
| 28 | + db.collection.update( { age: 20 }, { $inc: { age: 1 } }, { multi: true } ); |
| 29 | + db.collection.update( { name: "John" }, { $inc: { age: 2 } }, { multi: true } ); |
34 | 30 |
|
35 |
| - :operator:`$inc` accepts positive and negative incremental amounts. |
| 31 | + The first :method:`~db.collection.update()` operation increments the |
| 32 | + value of the ``age`` field by ``1`` for all documents in the |
| 33 | + collection that have an ``age`` field equal to ``20``. The |
| 34 | + second operation increments the value of the ``age`` field by ``2`` |
| 35 | + for all documents in the collection with the ``name`` field |
| 36 | + equal to ``"John"``. |
0 commit comments