Mongodb 如何一次更新多个子文档
发布于 14小时前 作者 booxood 57 次浏览 来自 问答

mongodb collection 的数据结构:

{
    "_id" : ObjectId("55718373d8a2c1b66a746d34"),
    "a" : "a1",
    "b" : {
        "b1" : [
            {
                "k1" : "v1",
                "k2" : "v2"
            },
            {
                "k1" : "v1",
                "k2" : "v2"
            }
        ],
        "b2" : [
            {
                "k1" : "v1",
                "k2" : "v2"
            },
            {
                "k1" : "no no no",
                "k2" : "v2"
            }
        ]
    }
}

如何更新把 ( b.b1.k1 = “v1” || b.b2.k1 == “v1” ) 的子文档都更新为 b.*.k2 = "ok"?

可能不太好理解,其实就是希望可以更新操作一次完成,变成下面这样:

{
{
    "_id" : ObjectId("55718373d8a2c1b66a746d34"),
    "a" : "a1",
    "b" : {
        "b1" : [
            {
                "k1" : "v1",
                "k2" : "ok"
            },
            {
                "k1" : "v1",
                "k2" : "ok"
            }
        ],
        "b2" : [
            {
                "k1" : "v1",
                "k2" : "ok"
            },
            {
                "k1" : "no no no",
                "k2" : "v2"
            }
        ]
    }
}
}

把 b1、b2 里 k1 == “v1” 的子文档的 k2 都更新成了 “ok” 。

回到顶部