使用mongoDB插入子文档 [英] insert in subdocument with mongoDB

查看:171
本文介绍了使用mongoDB插入子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在集合中有以下文件:

I have the following document in the collection:

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

如何在小部件中为名称3插入 {id:1,blabla:blabla}

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

推荐答案

与之前的答案相比,只需将所有内容插入到文档的根目录中,这是正确的方法与位置运营商

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"
   }
 }
});

这篇关于使用mongoDB插入子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆