Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$push equivalent for map in mongo

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?

like image 749
GJain Avatar asked Aug 02 '14 00:08

GJain


People also ask

What is $Push in MongoDB?

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.

Does MongoDB support maps?

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.

What is map in MongoDB?

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> } }

What is $Set in MongoDB?

$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.


1 Answers

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
    }
}
like image 173
Neil Lunn Avatar answered Sep 28 '22 15:09

Neil Lunn