Document.set()
Inserts a field into an existing document or changes the value of a field in an existing document.
Operations Performed
- 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.
- 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]}
Permissions Required
- The
readAce
andwriteAce
permissions on the volumes where the JSON tables that contain the documents are located. For information about how to set permissions on volumes, see Setting/Modifying Whole Volume ACEs. - readperm and writeperm on the specified field, if this field exists. See How to Obtain
readperm
andwriteperm
on a Field. - writeperm on the parent field, if the specified field does not exist. See How to Obtain
readperm
orwriteperm
on a Field.