private void GetOrCreateCollection <T>() { Connect(); string collectionName = typeof(T).Name; Logger.Trace($"{nameof(MongoStore)}.{nameof(GetOrCreateCollection)}<{typeof(T).Name}>", new LogItem("Event", "Mongo GetCollection")); IMongoCollection <T> collection = Database.GetCollection <T>(collectionName); Dictionary <string, List <string> > indexes = new Dictionary <string, List <string> > { { "ExpiresAt", new List <string> { "ExpiresAt" } } }; PropertyInfo[] members = typeof(T).GetProperties(); foreach (PropertyInfo memberInfo in members) { MongoIndexAttribute indexAttribute = memberInfo.GetCustomAttribute <MongoIndexAttribute>(); if (indexAttribute == null) { continue; } if (!indexes.ContainsKey(indexAttribute.IndexName)) { indexes.Add(indexAttribute.IndexName, new List <string>()); } indexes[indexAttribute.IndexName].Add(memberInfo.Name); } IMongoIndexManager <T> indexManager = collection.Indexes; foreach (KeyValuePair <string, List <string> > index in indexes) { bool indexExists = false; using (IAsyncCursor <BsonDocument> asyncCursor = indexManager.List()) while (asyncCursor.MoveNext() && !indexExists) { indexExists = CheckIndexExists(asyncCursor, index); } if (!indexExists) { string indexJson = $"{{{string.Join(",", index.Value.Select(field => $"\"{field}\":1"))}}}"; Logger.Trace($"{nameof(MongoStore)}.{nameof(GetOrCreateCollection)}<{typeof(T).Name}>", new LogItem("Action", $"Create ExpiresAt index")); CreateIndexOptions cio = new CreateIndexOptions { Name = index.Key }; if (index.Key == "ExpiresAt") { cio.ExpireAfter = TimeSpan.Zero; } indexManager.CreateOne(new JsonIndexKeysDefinition <T>(indexJson), cio); } } CollectionCache.Add(typeof(T), collection); }