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" }
db.x.save(mongo)

      

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?

+3


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();
mongo.y.push({title:"test2"});
db.x.save(mongo);

      

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

+2


source


you should use $push

for this:

{ $push : { field : value } }

      



http://www.mongodb.org/display/DOCS/Updating#Updating-%24push

+2


source







All Articles