Search code examples
c#mongodbthread-safetymongodb-.net-drivernosql

MongoDB C# Driver and Thread Safety


In the documentation for MongoClient, MongoServer, MongoDatabase and MongoCollection<T> I see that it's said that they are thread-safe.

Question: Does that mean I can have (for example) static fields of them in a class and access them from any Task/Thread?

Like:

public static MongoClient Client = new MongoClient(Properties.Settings.Default.MongoConnStr);
public static MongoServer Server = Client.GetServer();
public static MongoDatabase DraftDB = Server.GetDatabase("draftdb");
public static MongoCollection<MyDoc> Docs = Program.DraftDB.GetCollection<Location>("mydocs");

Specially about MongoCollection<T>; I want to be sure that something like var cursor = Docs.Find(query).SetLimit(50); does not perform a mutation on the MongoCollection<T> (It's static state to be precise).


Solution

  • From this page you know that MongoServer, MongoDatabase, MongoClient, MongoCollection and MongoGridFS are thread safe. MongoCursor is specifically not thread-safe.

    This means you can safely access them from multiple tasks without worrying about that changing their "state" - however you still have to take care around how to set or change their values.

    Specifically to your question, querying a collection (which returns a cursor object) does not mutate the MongoCollection object.