DocumentMutation.increment()

Increments the value of a numeric field by the amount of the specified value.

Operations Performed

  1. Verifies that a field at the specified path exists. If the field at the specified path does not exist, this operation creates it with the specified value.
  2. Verifies that the field is of the same numeric data type as the passed value.
  3. Adds the passed value to the existing value.

Example of Incrementing a Numeric Value in a Scalar Field

Original document
{ "_id" : "000001"; "views" : 1 }
Example code for the append
  public DocumentMutation buildDocumentMutation() {
    return MapRDB.newDocumentMutation()
      .increment("views", 1);
  }

  public void update(String tablePath, DocumentMutation mutation, String _id) {
    try(Table table = MapRDB.getTable(tablePath)) {
      table.update(_id, mutation);
    }
  }
Parameter Description
_id The value of the document's _id field.
tablePath The path of the table in the MapR file system. See Table Paths.
Revised document
{ "_id" : "000001"; "views" : 2 }

Example of Incrementing a Numeric Value in an Array

Original document
{ "_id" : "000001"; "scores" : [10,20,25] }
Example code for the append
  public DocumentMutation buildDocumentMutation() {
    return MapRDB.newDocumentMutation()
      .increment("scores[2]", 5);
  }

  public void update(String tablePath, DocumentMutation mutation, String _id) {
    try(Table table = MapRDB.getTable(tablePath)) {
      table.update(_id, mutation);
    }
  }
Revised document
{ "_id" : "000001"; "scores" : [10,20,30] }

Permissions Required

Link to Javadoc

DocumentMutation

IMPORTANT: If a DocumentMutation object modifies a field two or more times, only the final operation on that field is applied.

Example One

table.update() in the last line fails with error code 22:

DBDocument doc = MapRDB.newDocument()
        .set("int", 100)
        .set("date", new Date(1000))
        .set("string", "a string");

table.insertOrReplace("doc1", doc);

// Set different fields
DocumentMutation mutation = MapRDB.newDocumentMutation();
mutation.setOrReplace("string", 1000);
mutation.set("string", 2000);

table.update("doc1", mutation);

Example Two

This code results in the document {"string":"a string add3"}, rather than the document {"string":"a string add1 add2 add3"}.

DBDocument doc = MapRDB.newDocument()
        .set("string", "a string");

table.insertOrReplace("doc1", record);

DocumentMutation mutation = MapRDB.newDocumentMutation();
mutation.append("string", " add1");
mutation.append("string", " add2");
mutation.append("string", " add3");

table.update("doc1", mutation);