public BsonDocument GetBsonDocumentContainsId(Type t, int id) { var collections = GetBsonDocumentsByType(t); if (t.GetInterfaces().All(x => x != typeof(IHierarchyEntity))) { return(collections.FirstOrDefault()); } lock (CachedIds) { var cachedColl = CachedIds.FirstOrDefault(x => x.Value.Object.Any(y => y == id)); if (cachedColl.Value != null) { var collection = (from coll in collections let elemName = coll.Elements.FirstOrDefault(y => y.Name == "name") where elemName.Value.AsString == cachedColl.Key select coll).ToList().FirstOrDefault(); if (collection != null) { return(collection); } } } foreach (var document in collections) { var name = document.Elements.FirstOrDefault(y => y.Name == "name").Value.AsString; var col = _mongoDb.GetCollection <BsonDocument>(name); var filter = Builders <BsonDocument> .Filter.Eq("_id", id); var count = col.FindAsync(filter).Result.ToListAsync().Result.Count; lock (CachedIds) { if (!CachedIds.ContainsKey(name)) { CreateCachedIdsAsync(col, name); } } if (count == 1) { lock (CachedIds) { CachedIds.Remove(name); } CreateCachedIdsAsync(col, name); return(document); } } return(null); }
private static Task CreateCachedIdsAsync(IMongoCollection <BsonDocument> col, string name) { var task = new Task(() => { var projection = Builders <BsonDocument> .Projection.Include(new StringFieldDefinition <BsonDocument>("_id")); var cachedIdsCollection = new CachedObject <List <int> >() { Object = null, CachedPointTime = DateTime.Now }; var options = new FindOptions <BsonDocument, BsonDocument> { Projection = projection }; var result = col.FindAsync(x => true, options).Result.ToListAsync().Result; var idsList = new List <int>(); foreach (var bsd in result) { var elem = bsd.Elements.FirstOrDefault(y => y.Name == "_id"); idsList.Add(elem.Value.AsInt32); } cachedIdsCollection.Object = idsList; lock (CachedIds) { if (!CachedIds.ContainsKey(name)) { CachedIds.Add(name, cachedIdsCollection); } else { if (CachedIds[name].CachedPointTime < cachedIdsCollection.CachedPointTime) { CachedIds[name] = cachedIdsCollection; } } } }); task.Start(); return(task); }