Reputation: 8140
I have a MongoDocument X which has some instances of MongoEmbeddedDocument Y.
I now want to add an extra embeddeddocument Y to my X collection. I've tried the following code:
var mongo = db.x.findOne();
mongo.y = { title:"test" }
db.x.save(mongo)
The problem is that that piece of code will deleted my entire collection of y embeddeddocuments that I had. Is there someway I can add one without deleting the existing ones?
Upvotes: 3
Views: 1520
Reputation: 33155
Assuming you're using an array to store your y, you probably want to do a $push, something like:
var mongo = db.x.findOne();
db.x.update({_id:mongo._id}, {$push:{y:{title:"test2"}}});
If you want to save the whole record again, you can do it 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 a single update command.
Upvotes: 2
Reputation: 18820
you have to use $push
to do this:
{ $push : { field : value } }
http://www.mongodb.org/display/DOCS/Updating#Updating-%24push
Upvotes: 2