Databases Reference
In-Depth Information
Safe Operations
Suppose you are writing an ecommerce application. If someone orders something, the
application should probably take a little extra time to make sure the order goes through.
That is why you can do a “safe” version of these operations, where you check whether
there was an error in execution and attempt to redo them.
MongoDB developers made unchecked operations the default because
of their experience with relational databases. Many applications written
on top of relational databases do not care about or check the return
codes, yet they incur the performance penalty of their application wait-
ing for them to arrive. MongoDB pushes this option to the user. This
way, programs that collect log messages or real-time analytics don't have
to wait for return codes that they don't care about.
The safe version of these operations runs a getLastError command immediately fol-
lowing the operation to check whether it succeeded (see “Database Com-
mands” on page 93 for more on commands). The driver waits for the database re-
sponse and then handles errors appropriately, throwing a catchable exception in most
cases. This way, developers can catch and handle database errors in whatever way feels
“natural” for their language. When an operation is successful, the getLastError re-
sponse also contains some additional information (e.g., for an update or remove, it
includes the number of documents affected).
The same getLastError command that powers safe mode also contains
functionality for checking that operations have been successfully repli-
cated. For more on this feature, see “Blocking for Replica-
tion” on page 140 .
The price of performing “safe” operations is performance: waiting for a database re-
sponse takes an order of magnitude longer than sending the message, ignoring the
client-side cost of handling exceptions. (This cost varies by language but is usually fairly
heavyweight.) Thus, applications should weigh the importance of their data (and the
consequences if some of it is lost) versus the speed needed.
When in doubt, use safe operations. If they aren't fast enough, start
making less important operations fire-and-forget.
More specifically:
• If you live dangerously, use fire-and-forget operations exclusively.
 
Search WWH ::




Custom Search