$ push等价于mongo中的地图 [英] $push equivalent for map in mongo

查看:60
本文介绍了$ push等价于mongo中的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用$push(向数组中添加元素)更新为atomically update包含数组的单个文档

We can use $push (to add an element into an array) in update to atomically update a single document containing the array

但是,我找不到原子地add a new key到文档中地图的方法.

However, I could not find a way to atomically add a new key to a map in a document.

我可以

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

我只处理single document,但是该文档具有地图.

I am only dealing with a single document but that document has a map.

有没有办法自动更新(add a new key)地图?

Is there a way I can update (add a new key) map atomically?

推荐答案

> $set 的>点符号 > 运算符是处理单个元素的方式.

Dot notation with the $set operator is how you address individual elements.

获取以下文档:

{
    "_id": 1,
    "map": {
        "field2": 1
    }

}

要在地图上添加"field3",您需要像这样进行更新:

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

这篇关于$ push等价于mongo中的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆