MongoDB: Updating subdocument

You need to use the $ positional operator

For example:

update({ 
       _id: 7, 
       "comments._id": ObjectId("4da4e7d1590295d4eb81c0c7")
   },{
       $set: {"comments.$.type": abc}
   }, false, true
);

I didn’t test it but i hope that it will be helpful for you.

If you want to change the structure of document you need to use

db.collection.update( criteria,
objNew, upsert, multi )

Arguments:

criteria - query which selects the record to update;
objNew - updated object or $ operators (e.g., $inc) which manipulate the object
upsert - if this should be an "upsert"; that is, if the record does not exist, nsert it
multi - if all documents matching criteria should be updated

and insert new objNew with new structure. check this for more details

Leave a Comment