MongoDB: Does saving a document rewrite the whole document? MongoDB: Does saving a document rewrite the whole document? mongodb mongodb

MongoDB: Does saving a document rewrite the whole document?


You can update a single field in a document with $set. This will modify the field on disk. However, if the document grows beyond the size before the update, the document may have to be relocated on disk.

Meanwhile, here is what the documentation says about save versus update:

>// x is some JSON style object>db.mycollection.save(x); // updates if exists; inserts if new>>// equivalent to:>db.mycollection.update( { _id: x._id }, x, /*upsert*/ true );

References


This depends on a client library you are using. For example, Mongoid (ODM in ruby) is smart enough to only send fields that were changed (using $set command). It is sometimes too smart and doesn't catch changes that I made to nested hashes. But I've never seen it send unchanged fields.

Other libraries/drivers may behave differently.


I know this question is old, but it's very useful to know how it works to help you design your database structure. Here is the details about MongoDB's storage engine:https://docs.mongodb.com/v3.2/faq/storage/

The document answers the question. Basically, if you update an integer field in MongoDB, it will mark the page(normally 4k) in memory where the integer resides in to be dirty and it will write memory page to disk on the next disk flush. So, if your document size is very big, the chance is that it will only write partial of your document into disk.

However, there are many other cases. If you are padding more data to your document, there is chances that MongoDB needs to move the entire document to a new location for the document to grow. In that case, the entire document will be written to disk.