We can use $push
(to add an element into an array) in update to atomically
update
a single document containing the array
However, I could not find a way to atomically add a new key
to a map in a document.
I could
* read the document,
* read the map in it,
* update the map in my code and
* update the document in my code.
But that is not atomic.
I am only dealing with a single document
but that document has a map.
Is there a way I can update (add a new key)
map atomically?
The $push operator appends a specified value to an array. The $push operator has the form: { $push: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
MongoDB provides the mapReduce() function to perform the map-reduce operations. This function has two main functions, i.e., map function and reduce function. The map function is used to group all the data based on the key-value and the reduce function is used to perform operations on the mapped data.
Definition. $map. Applies an expression to each item in an array and returns an array with the applied results. The $map expression has the following syntax: { $map: { input: <expression>, as: <string>, in: <expression> } }
$set outputs documents that contain all existing fields from the input documents and newly added fields. The $set stage is an alias for $addFields. Both stages are equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields.
Dot notation with the $set
operator is how you address individual elements.
Take the following document:
{
"_id": 1,
"map": {
"field2": 1
}
}
In order to add "field3" to the map you update like this:
db.collection.update({ "_id": 1 }, { "$set": { "map.field3": 2 } })
So now your document looks like this:
{
"_id": 1,
"map": {
"field2": 1,
"field3": 2
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With