Document.set()

Inserts a field into an existing document or changes the value of a field in an existing document.

Operations Performed

  1. Verifies that a field at the specified path exists.
    • If there is no field, creates the field and write the new value to it.
    • If there is a field, proceeds to the next step.
  2. Verifies that the passed value is of the same data type as the existing value.
    • If the data types are identical, writes the new value.
    • If the data types are not identical, returns an exception.

First Example

Existing document
{ "_id" : "user000001", "a" : "value_a"}
Example code
// Create a Document object for the document with the _id field to change.
Document d = table.get("user000001");

// Change the value for field a.
d.set("a", "value_a2"); 

/* Replace the document with the new version of the document that contains
   the changed value. */
table.insertOrReplace(d);
Revised document
{ "_id" : "user000001", "a" : "value_a2"}

Second Example

You cannot use this method to change the value of the _id field in an existing document. The value of this field is immutable. If you try to change it, MapR-DB considers the resulting document to be a new document.

Existing document
{ "_id" : "user000001", "a" : "value_a"}
Example code
// Create a Document object for the document with the _id field to change.
Document d = table.get("user000001");

// Set a new value for the _id field.
d.set("_id", "user000100"); 

/* Try to replace the document with the new version of the document that contains the changed value of _id. */
table.insertOrReplace(d);
Result
{ "_id" : "user000001", "a" : "value_a"}
{ "_id" : "user000100", "a" : "value_a"}

Third Example

Original document
{ "_id" : "user000001", "a" : [1, 2, 3]}
Example code
// Create a Document object for the document with the _id field to change.
Document d = table.get("user000001");

// Set a new value at index 3 in the array a.
d.set("a[3]", 4); 

/* Try to replace the document with the new version of the document that contains the changed value of _id. */
table.insertOrReplace(d);
Result
{ "_id" : "user000001", "a" : [1, 2, 3, 4]}
NOTE: If an application tries to set a new value in an array and gives the value an index higher than (current largest index) + 1, then the value is given the index (current last index) + 1. For example, suppose that an application tries to set a value at index 5 in an array for which the current largest index is 2. MapR-DB assigns the value an index of 3 when inserting the value into the array.

Permissions Required

Link to Javadoc

Document