insert in subdocument with mongoDB

僤鯓⒐⒋嵵緔 提交于 2019-12-09 06:59:33

问题


I have the following document in the collection:

"_id" : "2",
"workspace" : [{
        "name" : "1",
        "widgets" : [ ]
    },{
        "name" : "2",
        "widgets" : [ ]
    },{
        "name" : "3",
        "widgets" : [ ]
    },{
        "name" : "4",
        "widgets" : [ ]
    }
]}

How can I insert {id: "1", blabla: "blabla"} in "widgets" for the "name" 3?


回答1:


In comparison to a previous answer which just inserts everything into the root of the document, here is a correct way to do this with positional operator:

db.t.update({
 "_id" : "2",
 "workspace.name" : "3"
},{
 $push: {
   'workspace.$.widgets' : {
       id: "2",
       blabla: "blabla"
   }
 }
});


来源:https://stackoverflow.com/questions/19709624/insert-in-subdocument-with-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!