$push equivalent for map in mongo

天涯浪子 提交于 2020-01-02 06:58:15

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/25090548/push-equivalent-for-map-in-mongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!