Skip to content

Mutation micro language

Ted Dunning edited this page Sep 12, 2015 · 3 revisions

Mutations are specified in a micro-language similar to the condition micro-language. If you want to set a field to a scalar value like a number or a string, you can simply say something like {"age": 34}. If you want to do something more elaborate, you need to replace the value of the field with an update expression. The most common update expression is something like {"$setOrReplace": ['a','b']} but you could also append a string to a field value, increment a number or delete the field entirely.

{"field" : { "$set" : "value"}  }
{"age" : { "$set" : 34}  }  // set age to 34
{"age" : { "$set" : 34} , "country" : { "$set": "USA"}  }  // set age to 34 and country to USA
{ "interests" : { "$set" : ["x", "y"] } } // set interests to an array
{ "address" : { "$set" : { "t" : "home"} } } // set address to an Object

{"field" : { "$setOrReplace" : "value"}  }
{"age" : { "$setOrReplace" : 34}  }  // set age to 34
{"age" : { "$setOrReplace" : 34, "country" : { "$setOrReplace" : "USA"}  }  // set age to 34 and country to USA

{ "field" : { "$append" : "value" }}
{ "name" :  { "$append" : "Doe" }} //  append Doe to the string if string or array if array eg: "John" = "JoeDoe" OR ["John"] = ["John" , "Doe"]

{"field" : { "$setOrReplace" : "value"}  }
{"age" : { "$setOrReplace" : 34}  }  // set age to 34
{"age" : { "$setOrReplace" : 34, "country" : { "$setOrReplace" : "USA"}  }  // set age to 34 and country to USA

{"field" : { "$inc" : value } }
{"age" : { "$inc" : 1 } } //  increment one value by a specified amount
{"age" : { "$delete": [] }

The following mutation operations are supported

Operation Meaning
$set Sets the value of a field if no previous value exists.
$setOrReplace Sets the value of a field conditionally. If a previous value exists, it is over-written
$inc Increments a numerical field value by the specified value. The previous value of the field must be a number.
$append Appends to a string-valued field. The argument must be a string since no type coercion is done.
$delete Deletes a field value. Note that due to the way that updates are represented, you need to provide some kind of argument such as {$delete:[]} or {$delete:1}.

Clone this wiki locally