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。