Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 更新嵌套列表会生成对象而不是数组_Mongodb - Fatal编程技术网

Mongodb 更新嵌套列表会生成对象而不是数组

Mongodb 更新嵌套列表会生成对象而不是数组,mongodb,Mongodb,我正在尝试使用此查询从嵌套在另一个列表中的列表更新字段: db.getCollection('TABLENAME').update({ "_id": ObjectId("5e5f8007bfe44c1628290ca9") }, { "$set": { "outerList.0.innerList.0.code": "c8" } }) 当innerList=null时出现问题。在这种情况下,将创建innerList,但它不是array,而是一个对象: {

我正在尝试使用此查询从嵌套在另一个列表中的列表更新字段:

db.getCollection('TABLENAME').update({
    "_id": ObjectId("5e5f8007bfe44c1628290ca9")
}, {
    "$set": {
        "outerList.0.innerList.0.code": "c8"
    }
})
innerList=null
时出现问题。在这种情况下,将创建innerList,但它不是array,而是一个对象:

{
    outerList: [
        {
            innerList: {
                "0": {
                    code: 'c8'
                }
            }
        }
    ]
}

如何确保innerList始终是一个数组?

我认为您需要使用
push
而不是
set
。解决方案如下所示:

> db.test2.insert({"_id":ObjectId("5e5fa4755d801f5c672addbb"),"outerList": []})
WriteResult({ "nInserted" : 1 })
> db.test2.find()
{ "_id" : ObjectId("5e5fa4755d801f5c672addbb"), "outerList" : [ ] }
> db.test2.update({"_id": ObjectId("5e5fa4755d801f5c672addbb")}, {"$push": {"outerList.0.innerlist":{"0":"c8"}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test2.find()
{ "_id" : ObjectId("5e5fa4755d801f5c672addbb"), "outerList" : [ { "innerlist" : [ { "0" : "c8" } ] } ] }
可以看出,
innerlist
是一个数组


如果有帮助,请告诉我

是的,如果innerList为null,它似乎会将其初始化为array。