问题
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