MongoDB: Does a document save a document to overwrite the entire document?

I have a domain collection with documents that contain domain information. Some of them are historical whois records, which can be zero or more and, of course, occupy most of the space for the document.

If I download the entire document, change something small (for example, update the field with numbers), and using the save() method will mongo clear the entire document to disk or only update BSON, which has changed? Ultimately, my question is, should I complicate my code with update() to save on I / O, or use only save() ?

This is not purely due to laziness, the document (after it is read in its entirety) goes through a series of steps for changing / processing the document, and if any changes have been made, the entire document will be saved. But if the cost of saving a document is high, I might have to think about it differently ...

+6
source share
3 answers

You can update a single field in a document with $set . This will change the field on the disk. However, if the document is larger than the size before updating, the document may need to be moved to disk .

Meanwhile, here's what the save versus update documentation says :

 >// 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

+4
source

It depends on the client library you are using. For example, Mongoid (ODM in ruby) is smart enough to send only those fields that have been changed (using the $set command). This is sometimes too smart and does not cause the changes I made for nested hashes. But I never saw him send immutable fields.

Other libraries / drivers may behave differently.

+2
source

I know this question is old, but it’s very useful to know how it works to help you create the structure of your database. Here are the details of the MongoDB storage device: 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 (usually 4k) in memory, where the integer is in a dirty state, and it will write the memory page to disk on the next disk. Thus, if the size of your document is very large, it is likely that it will only write a partial document to disk.

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

0
source

Source: https://habr.com/ru/post/918904/


All Articles