×

mongodb批量修改数组下元素某个字段值

mongodb批量修改数组下元素某个字段值

mtsym mtsym 发表于2018-08-31 15:45:59 浏览7869 评论0

抢沙发发表评论

mongodb批量修改数组下元素某个字段

例如下面的数据,如果想把alias为ooo的des都改成haha

{
    "name": "test",
    "items": [
        {
            "id": 1,
            "content": {
                "cid": "123", 
                "des": "hello",
                "alias": "ooo"
            }
        },
        {
            "id": 2,
            "content": {
                "cid": "124", 
                "des": "world",
                "alias": "ooo"
            }
        }
    ]
}

查找操作,通过elemMatch处理,如下

db.test.find({"items":{$elemMatch:{"content.alias": "ooo"}}})

修改操作,通过$符来操作

db.test.find({"items":{$elemMatch:{"content.alias": "ooo"}}},{$set:{"items.$.content.des":"haha"}}, {multi: true})

一不小心加错了字段可以用删除

db.test.update({"items":{$elemMatch:{"content.alias": "ooo"}}},{$unset:{"xxxx":""}},false,true)

群贤毕至

访客