Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Does saving a document rewrite the whole document?

Tags:

mongodb

I have the collection domain with documents that contain domain information. Part of that is the historical whois records, which may be zero or more and by far take up the majority of the space for the document.

If I load the entire document, change something small (like update a number field) and use the save() method will mongo flush the entire document to disk or only update the BSON that has changed? Ultimately my question is, should I bother complicating my code with update()'s to save on I/O or should I just use save()?

This isn't purely due to lazyness, the document (after it gets read in entirety) goes through a series of steps to modify/process the document and if any changes have been made the entire document is saved. But if the cost of saving the document is high then maybe I have to think about it a different way...

like image 302
Elliot Chance Avatar asked Jun 25 '12 02:06

Elliot Chance


1 Answers

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

  • Save versus update
  • The $set Modifier Operation
  • Padding Factor
like image 68
fdsaas Avatar answered Sep 23 '22 07:09

fdsaas