Nick Nick - 1 year ago 35
Node.js Question

Insert object into MongoDB object's array

I'm trying to add an object into an empty array that is stored in one of my collections.

Currently this is how I have my collection setup:

[
{
"name": "user_added",
"DRGs": []
},
...
]


How can I insert an object into the collection so that it looks like this;

[
{
"name": "user_added",
"DRGs": [
{
"code": "491",
"name": "Back & neck procedures"
}
]
},
...
]

Answer

Check out $push documentation.

You should be able to accomplish your goal with the following:

var collectionName = 'users'; // or whatever your actual collection name is
var objectToPush = {
   code: "491",
   name: "Back & neck procedures"
};

db.collection(collectionName).updateOne(
    {"name": "user_added"}, 
    { $push: { "DRGS": objectToPush }}
);