关于mongodb更新数组里的所有对象内容问题。。。。
发布于 6 年前 作者 oxgos 5563 次浏览 来自 问答

###文档如下:

{
    name: 4,
    list: [{
        id: "a",
        date: 1504195200000,
        other: "c"
    },{
        id: "b",
        date: 1504195200000,
        other: "c"
    }]
}

如何把list数组下的元素里的other全部一次性更新呢? 尝试了以下方法:不行…

db.getCollection('test').update({'name': 4}, {$set: {'list.$.other': 'a'}}, {multi: true})

不知道为什么?求大神的解决方法,谢谢

7 回复

MongoDB 3.6 版本的话可以这样 db.test.update({name: 4}, {$set: {‘list.$[].other’: ‘a’}}, {multi: true})

@beyond5959 谢谢大神,终于好了,原来3.6新特性有…一直没注意

@beyond5959 求助为什么我还是不行,版本是3.6.0

db.tests.find() { “_id” : ObjectId(“5a38a44f90b8cc9c05da6703”), “name” : 4, “list” : [ { “id” : “a”, “date” : 1504195200000, “other” : “c” }, { “id” : “b”, “date” : 1504195200000, “other” : “c” } ] } db.version() 3.6.0 db.tests.update({name: 4}, {$set: {‘list.$[].other’: ‘a’}}, {multi: true}) WriteResult({ “nMatched” : 0, “nUpserted” : 0, “nModified” : 0, “writeError” : { “code” : 16837, “errmsg” : “cannot use the part (list of list.$[].other) to traverse the element ({list: [ { id: “a”, date: 1504195200000.0, other: “c” }, { id: “b”, date: 1504195200000.0, other: “c” } ]})” } })

回到顶部