Operators: $inc

Incrementing (or decrementing) the value of a numeric field in a document.

🪶 The $inc operator is used to increment (or decrement, if a negative number is provided) the value of a numeric field in a document.

NOTE: You can only use the $set, $inc operators in document update methods such as the update, modify and replace methods .


Database: Client > model: Users

Here we will simulate a database with the Users collection:
1
  • COLLECTION:
  • Users > [
    2  
  • {
  • name:
  • "Christopher Axxwell",
  • age:
  • 27
  • .
  • 4
  • ,
  • pets:
  • 'cat'  
  • }
  • ,
    3  
  • {
  • name:
  • "Chris Buckman",
  • age:
  • 22
  • ,
  • pets:
  • 'cat'
  • }
  • ,
    4  
  • {
  • name:
  • "Santiago Smith",
  • age:
  • 26
  • ,
  • pets:
  • 'dog'
  • }
  • ,
    5   ...
    6]

    Query the above database:

    1
  • import
  • MerlinDB,
  • {
  • Schema
  • }
  • from
  • "@chrisaxxwell/merlin-db";
    2
  • //Or if you are using 'merlindb.max.js' just call 'new MerlinDB()';
  • 3
    4
  • const
  • merlin =
  • new
  • MerlinDB(
  • )
  • ;
    5merlin
  • .connect(
  • "Client"
  • )
  • ;
    6
  • var
  • clientModel = merlin
  • .model(
  • "Users", <userSchema>
  • )
  • ;
    7
    8
  • //$inc: <object>;
  • 9clientModel
  • .updateOne(
  • 10  
  • {
  • name:
  • "Christopher Axxwell"
  • }
  • ,
    11  
  • {
  • 12      
  • $set:
  • {
  • name:
  • "Chris Axxwell"
  • }
  • ,
    13      
  • $inc:
  • {
  • age:
  • 1
  • }
  • ,
    14  
  • }
  • 15
  • )
  • .then(
  • e => console
  • .log(
  • e
  • )
  • )
  • ;
    16
    17______________________________
    18
    19
  • COLLECTION:
  • Users > [
    20  
  • {
  • name:
  • "Chris Axxwell",
  • age:
  • 28
  • .
  • 4
  • ,
  • pets:
  • 'cat'  
  • }
  • ,
    21  
  • {
  • name:
  • "Chris Buckman",
  • age:
  • 22
  • ,
  • pets:
  • 'cat'
  • }
  • ,
    22  
  • {
  • name:
  • "Santiago Smith",
  • age:
  • 26
  • ,
  • pets:
  • 'dog'
  • }
  • ,
    23   ...
    24]