C# Driver mongo-csharp-driver, when to create server, database and collection objects

66 views
Skip to first unread message

mamu

unread,
Nov 8, 2010, 5:31:40 PM11/8/10
to mongodb-user
We have asp.net application and experimenting with mongodb using
official c# driver.

Question is

MongoServer
MongoDatase
MongoCollection

All this are thread safe.

What is suggested scope of those objects. per application or per call?

Should i create an instance of all of above in application startup or
it needed to be created with every request? Could there be any issue
if multiple threads same instance of any of above class?

Robert Stam

unread,
Nov 8, 2010, 7:26:42 PM11/8/10
to mongodb-user
The three classes you mention are all thread safe. You could save them
somewhere in your application, or simply fetch them again when you
need them. In particular:

1. Every time MongoServer.Create is called with the same connection
string it returns the same instance
2. Every time GetDatabase is called with the same databaseName/
credentials combination it returns the same instance
2. Every time GetCollection is called with the collectionName/
TDefaultDocument combination name it returns the same instance

So you would only be saving a small amount of lookup overhead if you
store these values in your own variable somewhere. Choose whatever is
easiest.

One thing that you shouldn't do is put any of these values in session
state because they are not Serializable.

Nat

unread,
Nov 8, 2010, 8:47:37 PM11/8/10
to mongodb-user
Does it mean that
- Collection<T> is thread-safe?
- Enumerator is safe to pass across threads?
- if there are multiple concurrent requests to a collection in
multiple threads, they may create a contention on
ConnectionPool.GetConnection as there is no easy way to obtain a
connection at the beginning of the work and return it at the end?

Robert Stam

unread,
Nov 8, 2010, 8:55:52 PM11/8/10
to mongodb-user
MongoCollection<TDefaultDocument> is thread safe.

The MongoCursor returned by a query is NOT thread safe (but can be
passed to a different thread to do the enumeration), and different
threads can be enumerating different cursors in parallel.

Don't think there would be contention on the connection pool. More
connections can be created.

If you want to reserve a connection for a thread to use for a series
of related operations use MongoDatabase.RequestStart/RequestDone (same
as the Java driver).

Nat

unread,
Nov 8, 2010, 9:00:07 PM11/8/10
to mongodb-user
Thanks. There should be a way to configure the minimum/maximum number
of connections though as it might overload mongod.

mamu

unread,
Nov 9, 2010, 10:11:02 AM11/9/10
to mongodb-user
Thanks,

Then i better off calling MongoServer.Create as it is not going to do
new connection for every MongoServer.Create instance.
Reply all
Reply to author
Forward
0 new messages