I found that some methods of the official MongoDB C# driver use SafeMode
and return SafeModeResult
. What is this SafeMode
and how do I use it? It would be great to see some use cases - for example, a use case with the RemoveAll
method of a MongoCollection
.
Safemode is only relevant when writing to the db.
For speed, if safemode is off and a write operation fails the driver doesn't wait around to care. Net effect is no exception gets thrown and you don't know you have an error.
Safemode set to on will force the driver to wait for a success confirmation, and if an error occurred will throw an exception.
Use safemode for data you care about (user accounts, orders, etc).
Don't use safemode for data that isn't essential (logging, usage stats etc)
MongoDB's default behavior is to have safemode off.
From documentation:
There are various level of SafeMode, and this class is used to represent those levels. SafeMode applies only to operations that don't already return a value (so it doesn't apply to queries or commands). It applies to the following MongoCollection methods: Insert, Remove, Save and Update.
The gist of SafeMode is that after an Insert, Remove, Save or Update message is sent to the server it is followed by a GetLastError command so the driver can verify that the operation succeeded. In addition, when using replica sets it is possible to verify that the information has been replicated to some minimum number of secondary servers.
The SafeMode class has static properties and methods that let you easily access common modes or create your own:
* SafeMode.False * SafeMode.True * SafeMode.WaitForReplications(int n)
The value for "n" includes the primary, so typically you want n >= 2.
I hope this is enough to understand the purpose of SafeMode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With