MongoDB .NET – Get IMongoCollection by Name

I’m refactoring some legacy code away from the MongoDB.Driver.Legacy API.

I’ve got the following method, which gets a MongoCollection by string collection name.

    protected virtual MongoCollection GetMongoCollection(Type type)     {         return Store.GetCollection(GetCollectionName(type));     } 

Store in this example is a MongoDatabase from the Legacy API. The GetCollectionName() method looks up various things in BsonClassMap to determine the string name of the collection:

    private string GetCollectionName(Type type)     {         return !IsRegisteredWithClassMap(type) ? type.Name : GetRegisteredClassMapType(type).Name;     }      private Type GetRegisteredClassMapType(Type objectType)     {         if (objectType.BaseType == null)         {             return null;         }         var isroot = BsonClassMap.LookupClassMap(objectType.BaseType).IsRootClass;         return isroot ? objectType.BaseType : GetRegisteredClassMapType(objectType.BaseType);     }      private bool IsRegisteredWithClassMap(Type objectType)     {         var isRegistered = GetRegisteredClassMapType(objectType);         return isRegistered != null;     } 

How would I implement the GetMongoCollection() method using the new API. The IMongoDatabase from the new API doesn’t have a GetCollection() method which accepts a string. Only a Generic version GetCollection<T>

Add Comment
1 Answer(s)

try this:

protected virtual MongoCollection GetMongoCollection(Type type) {     var method = typeof(IMongoDatabase).GetMethod("GetCollection");     var result = method.MakeGenericMethod(type).Invoke(yourMongoDbInstance);     return (MongoCollection) result; } 

if you can afford more effort just change the previous method signature in this way:

protected virtual MongoCollection GetMongoCollection<T>() {    return yourMongoDbInstance.GetCollection<T>(); } 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.