More complex update operations
We already learned how to add attributes or change the value of attributes in existing documents:
collection.update( {'n': /^#1/}, {'$set': {'v': 5} }, {'multi': true}, function (err, count) { // ... }
This would set the value of the v
attribute to 5
for all documents whose n
value starts with #1
.
This is probably the most regularly used update operation. Some other ways to update documents are available, however. Numeric attributes can be increased, for example:
collection.update( {'n': /^#1/}, {'$inc': {'v': +1} }, {'multi': true}, function (err, count) { // ... }
There is no $dec
operation, but of course, we can increase by -1
:
collection.update( {'n': /^#1/}, {'$inc': {'v': -1} }, {'multi': true}, function (err, count) { // ... }
Multiplication is possible, too:
collection.update( {'n': /^#1/}, {'$mul': {'v': 2} }, {'multi': true}, function (err, count) { // ... }
There are several other operators:
$rename...