Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert an embedded document to a new field in mongodb document

I have a document in mongodb collection like this:

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

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

I'm a newcomer to mongodb. Please help.

like image 327
s.k.paul Avatar asked Nov 17 '14 07:11

s.k.paul


1 Answers

You can do it with

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

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

Your result document will be

{
    "_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
}

Step 1 : add new field: PackSizes is an array

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

Step 2: push new item to array

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

and you will have

{
    "_id" : 133,
    "Name" : "abc",
    "Price" : 20,
    "PackSizes" : [ 
        {
            "_id" : 123,
            "PackSizeName" : "xyz",
            "UnitName" : "pqr"
        }, 
        {
            "_id" : 124,
            "PackSizeName" : "xyz",
            "UnitName" : "pqr"
        }
    ]
}
like image 103
2 revs, 2 users 67% Avatar answered Sep 28 '22 13:09

2 revs, 2 users 67%