【问题标题】:$push equivalent for map in mongo$push 等效于 mongo 中的地图
【发布时间】:2014-08-02 00:44:05
【问题描述】:

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

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

我可以

* read the document,
* read the map in it, 
* update the map in my code and 
* update the document in my code.

但这不是原子的。

我只处理single document,但该文档有一张地图。

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

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    Dot notation$set 运算符是您处理单个元素的方式。

    带上以下文件:

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

    为了将“field3”添加到您更新的地图中,如下所示:

    db.collection.update({ "_id": 1 }, { "$set": { "map.field3": 2 } })
    

    所以现在你的文档看起来像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多