MongoDB Add additional embedded document instead of overwriting it

I have MongoDocument X that has some instances of MongoEmbeddedDocument Y.

Now I want to add an additional inline document Y to my X collection. I have tried the following code:

var mongo = db.x.findOne();
mongo.y = { title:"test" }


The problem is that this piece of code will delete my entire collection of y inline documents that I had. Is there a way to add one without removing the existing ones?


source to share

2 answers

Assuming you are using an array to hold y, you probably want to do $ push, something like:

var mongo = db.x.findOne();
db.x.update({_id:mongo._id}, {$push:{y:{title:"test2"}}});


If you want to save the entire entry again, you can do this closer to what you were trying:

var mongo = db.x.findOne();


But $ push is probably better and you can do it in one update command.



you should use $push

for this:

{ $push : { field : value } }



All Articles