将嵌入式文档插入到mongodb文档中的新字段

将嵌入式文档插入到mongodb文档中的新字段

本文介绍了将嵌入式文档插入到mongodb文档中的新字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mongodb集合中有一个文档,如下所示:

I have a document in mongodb collection like this:

{
   _id: 133,
   Name: "abc",
   Price: 20
}

我想添加一个新字段"PackSizes",该字段可能是或可能不是是数组类型,然后要在其中嵌入文档.喜欢-

I would like to add a new field "PackSizes" which may be or not may be of an array type, and then would like to an embedded document in it. Like-

PackSizes:
         [
             {_id: 123, PackSizeName:"xyz", UnitName:"pqr"}
         ]

or,

PackSizes:  {_id: 123, PackSizeName:"xyz", UnitName:"pqr"}

我是mongodb的新手.请帮忙.

I'm a newcomer to mongodb. Please help.

推荐答案

您可以使用

db.test.update(
   { _id : 133 },
   { $set : { PackSizes:  {_id: 123, PackSizeName:"xyz", UnitName:"pqr"}} }
)

PackSizes可以是任何文档,带有数组或不带有数组.

PackSizes could be any document, with array or without it.

您的结果文档将是

{
    "_id" : 133,
    "Name" : "abc",
    "Price" : 20,
    "PackSizes" : {
        "_id" : 123,
        "PackSizeName" : "xyz",
        "UnitName" : "pqr"
    }
}

已更新:要添加新字段和数组成员,

Updated:For add new field and a member to array,

假设我们有您的原始文件

Assume we have your original document

{
   _id: 133,
   Name: "abc",
   Price: 20
}

第1步:添加新字段:PackSizes是一个数组

Step 1 : add new field: PackSizes is an array

db.test.update(
   { _id : 133 },
   { $set : {PackSizes: [ {_id: 123, PackSizeName:"xyz", UnitName:"pqr"}]}}
)

第2步:将新项目推送到数组

Step 2: push new item to array

db.test.update(
   { _id : 133 },
   { $push : { PackSizes: {_id: 124, PackSizeName:"xyz", UnitName:"pqr"}} }
)

您将拥有

{
    "_id" : 133,
    "Name" : "abc",
    "Price" : 20,
    "PackSizes" : [
        {
            "_id" : 123,
            "PackSizeName" : "xyz",
            "UnitName" : "pqr"
        },
        {
            "_id" : 124,
            "PackSizeName" : "xyz",
            "UnitName" : "pqr"
        }
    ]
}

这篇关于将嵌入式文档插入到mongodb文档中的新字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:46