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.
In your Json structure _id is mongoDB immutable field so in your case if you changed _id to simply id and _id represents mongo id then following javascript may solve your problem
If you achieve your output as given by you then first you should unset your documents and then set update
You can do it with
PackSizes could be any document, with array or without it.
Your result document will be
Updated: For add new field and a member to array,
Assume we have your original document
Step 1 : add new field: PackSizes is an array
Step 2: push new item to array
and you will have