How do I use SafeMode with the MongoDB C# driver
Asked Answered
S

3

15

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.

Subsidence answered 5/1, 2011 at 14:2 Comment(0)
B
29

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.

Burro answered 6/1, 2011 at 0:52 Comment(0)
I
24

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.

Ium answered 5/1, 2011 at 14:20 Comment(0)
A
2

SafeMode appears to be obsolete.

The equivalent is WriteConcern.Acknowledged on MongoClientSettings (typically passed to the MongoClient constructor). Acknowledged is the default WriteConcern in the current version of the driver (2.2.4).

See also MongoDb SafeMode compare to WriteConcern

Arouse answered 14/6, 2016 at 17:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.