Service » Atomic operations

Atomically increment or decrement numeric fields on a document without reading and re-writing the whole model.

About atomic operations

Mondoc exposes atomic increment and decrement helpers that map directly to MongoDB's $inc operator. Because the update is issued as a single database command, you never need to fetch the document first — making these methods safe for concurrent use and far more efficient than a read-modify-write cycle.

All methods are public static and available on every service that extends MondocAbstractService.

Increment

  • inc(ObjectId $id, string $field, int $delta = 1): bool
    Increments a single numeric field by $delta (default 1). Returns true on success. You may pass a negative $delta to decrement via this method if you prefer.
  • incMulti(ObjectId $id, array $fieldsToDeltas): bool
    Increments multiple fields in a single database operation. $fieldsToDeltas is an associative array mapping field names to their integer deltas.
<?php
// Increment 'loginCount' by 1
MyService::inc($model->getObjectId(), 'loginCount');

// Increment 'views' by 5
MyService::inc($model->getObjectId(), 'views', 5);

// Increment 'loginCount' and 'points' in one operation
MyService::incMulti($model->getObjectId(), [
    'loginCount' => 1,
    'points'     => 10,
]);

Decrement

  • dec(ObjectId $id, string $field, int $delta = 1): bool
    Decrements a single numeric field by $delta (default 1). The $delta is always treated as a positive whole number — passing 3 reduces the field value by 3.
  • decMulti(ObjectId $id, array $fieldsToDeltas): bool
    Decrements multiple fields in a single database operation. Like dec(), each delta in the array is treated as a positive whole number that will be subtracted.
<?php
// Decrement 'stock' by 1
MyService::dec($model->getObjectId(), 'stock');

// Decrement 'stock' by 3
MyService::dec($model->getObjectId(), 'stock', 3);

// Decrement 'stock' and 'reservedCount' in one operation
MyService::decMulti($model->getObjectId(), [
    'stock'         => 1,
    'reservedCount' => 1,
]);

inc() accepts negative deltas, so inc($id, 'score', -5) is equivalent to dec($id, 'score', 5). Use whichever reads more clearly in context.