Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use SafeMode with the MongoDB C# driver

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.

like image 864
Edward83 Avatar asked Jan 05 '11 14:01

Edward83


2 Answers

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.

like image 56
sym3tri Avatar answered Sep 29 '22 21:09

sym3tri


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.

like image 45
Andrew Orsich Avatar answered Sep 29 '22 19:09

Andrew Orsich