Exemple #1
0
        /// <summary>
        /// 更新索引
        /// </summary>
        /// <param name="collection">集合名</param>
        /// <param name="key"></param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public string UpdateIndex <T>(string collection, Expression <Func <T, object> > key, bool asc = true)
        {
            IMongoIndexManager <T> mgr = Database.GetCollection <T>(collection).Indexes;

            return(mgr.CreateOne(new CreateIndexModel <T>(asc
                ? Builders <T> .IndexKeys.Ascending(key)
                : Builders <T> .IndexKeys.Descending(key))));
        }
Exemple #2
0
        /// <summary>
        /// 更新索引
        /// </summary>
        /// <param name="collection">集合名</param>
        /// <param name="index">索引键</param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public async Task <string> UpdateIndexAsync(string collection, string index, bool asc = true)
        {
            IMongoIndexManager <BsonDocument> mgr = Database.GetCollection <BsonDocument>(collection).Indexes;

            return(await mgr.CreateOneAsync(new CreateIndexModel <BsonDocument>(asc
                ? Builders <BsonDocument> .IndexKeys.Ascending(doc => doc[index])
                : Builders <BsonDocument> .IndexKeys.Descending(doc => doc[index]))));
        }
Exemple #3
0
        public static IMongoIndexManager <TDocument> Add <TDocument>(this IMongoIndexManager <TDocument> indexManager,
                                                                     string path)
        {
            indexManager.CreateOne(new CreateIndexModel <TDocument>(
                                       new IndexKeysDefinitionBuilder <TDocument>()
                                       .Ascending(new StringFieldDefinition <TDocument>(path))
                                       ));

            return(indexManager);
        }
 public static async Task TryDropOneAsync <T>(this IMongoIndexManager <T> indexes, string name)
 {
     try
     {
         await indexes.DropOneAsync(name);
     }
     catch
     {
         /* NOOP */
     }
 }
Exemple #5
0
        /// <summary>
        /// 创建索引
        /// </summary>
        /// <param name="collection">集合名</param>
        /// <param name="index">索引键</param>
        /// <param name="key"></param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public async Task <string> CreateIndexAsync <T>(string collection, string index, Expression <Func <T, object> > key, bool asc = true)
        {
            IMongoIndexManager <T> mgr = Database.GetCollection <T>(collection).Indexes;
            var list = mgr.List();

            while (list.MoveNext())
            {
                if (!list.Current.Any(doc => doc["name"].AsString.StartsWith(index)))
                {
                    return(await mgr.CreateOneAsync(new CreateIndexModel <T>(asc ? Builders <T> .IndexKeys.Ascending(key) : Builders <T> .IndexKeys.Descending(key))));
                }
            }
            return(String.Empty);
        }
Exemple #6
0
 public override void UpdateIndexes <T>(IMongoIndexManager <T> indexes)
 {
     if (!indexesUpdated)
     {
         lock (IndexLock)
         {
             if (!indexesUpdated)
             {
                 var index = indexes.CreateOneAsync(Builders <T> .IndexKeys.Ascending("UserName")).Result;
                 indexesUpdated = true;
             }
         }
     }
 }
Exemple #7
0
        /// <summary>
        /// 创建索引
        /// </summary>
        /// <param name="collection">集合名</param>
        /// <param name="index">索引键</param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public async Task <string> CreateIndexAsync(string collection, string index, bool asc = true)
        {
            IMongoIndexManager <BsonDocument> mgr = Database.GetCollection <BsonDocument>(collection).Indexes;
            var list = mgr.List();

            while (list.MoveNext())
            {
                if (!list.Current.Any(doc => doc["name"].AsString.StartsWith(index)))
                {
                    return(await mgr.CreateOneAsync(new CreateIndexModel <BsonDocument>(asc ? Builders <BsonDocument> .IndexKeys.Ascending(doc => doc[index]) : Builders <BsonDocument> .IndexKeys.Descending(doc => doc[index]))));
                }
            }
            return(string.Empty);
        }
Exemple #8
0
        void AssertIndexIsCorrect <T>(IMongoIndexManager <T> indexes, string propertyToIndex)
        {
            var indexInfo = indexes.Single(i => IsIndexForProperty(propertyToIndex, i));

            if (!indexInfo.IsUnique)
            {
                throw new InvalidOperationException(string.Format("The index for {0} already existed, but it wasn't enforcing a UNIQUE constraint.", propertyToIndex));
            }

            if (indexInfo.IsBackground)
            {
                throw new InvalidOperationException(string.Format("The index for {0} aready exists, but it wasn't SYNCHRONOUS.", propertyToIndex));
            }
        }
        public static void SetIndices <TDocument>(this IMongoIndexManager <TDocument> indexManager, IList <Tuple <IndexKeysDefinition <TDocument>, CreateIndexOptions <TDocument> > > indices) where TDocument : IDocument
        {
            foreach (var index in indices)
            {
                try
                {
                    var indexModel = new CreateIndexModel <TDocument>(index.Item1, index.Item2);

                    indexManager.CreateOne(indexModel);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
 public static void CreateOrUpdate <T>(this IMongoIndexManager <T> indexes, CreateIndexModel <T> indexModel)
 {
     try
     {
         indexes.CreateOne(indexModel);
     }
     catch (MongoCommandException ex)
     {
         if (ex.CodeName == "IndexOptionsConflict")
         {
             string name = ex.Command["indexes"][0]["name"].AsString;
             indexes.DropOne(name);
             indexes.CreateOne(indexModel);
         }
         else
         {
             throw;
         }
     }
 }
        public static bool checkIndexes()
        {
            IMongoDatabase db = MongoTools.connect("mongodb://localhost", "climaColombia");
            //clean up bog buc with PA variable
            List <string> collNames       = MongoTools.collectionNames(db);
            int           withindex       = 0;
            int           cleanCollection = 0;

            foreach (string collection in collNames)
            {
                if (collection.Contains("Clean"))
                {
                    cleanCollection++;
                    var coll = db.GetCollection <BsonDocument>(collection);
                    IMongoIndexManager <BsonDocument> index = coll.Indexes;

                    using (IAsyncCursor <BsonDocument> cursor = coll.Indexes.List())
                    {
                        while (cursor.MoveNext())
                        {
                            IEnumerable <BsonDocument> batch = cursor.Current;
                            foreach (BsonDocument b in batch)
                            {
                                if (b["key"].AsBsonDocument.Contains("time"))
                                {
                                    withindex++;
                                }
                            }
                        }
                    }
                }
            }
            bool success = false;

            if (withindex == cleanCollection)
            {
                success = true;
            }
            return(success);
        }
Exemple #12
0
 public static IMongoIndexManager <TDocument> Add <TDocument, TArrayDocument>(this IMongoIndexManager <TDocument> indexManager,
                                                                              Expression <Func <TDocument, IEnumerable <TArrayDocument> > > targetArray, Expression <Func <TArrayDocument, object> > targetField)
 {
     return(indexManager.Add(Path.From(targetArray, targetField)));
 }
Exemple #13
0
        public static void AddCompletedTaskIndexes(this IMongoIndexManager <CompletedEnglishTaskEntity> indexesConfiguration)
        {
            var index = Builders <CompletedEnglishTaskEntity> .IndexKeys.Ascending(x => x.UserId);

            indexesConfiguration.CreateOne(new CreateIndexModel <CompletedEnglishTaskEntity>(index));
        }
Exemple #14
0
 public abstract void UpdateIndexes <T>(IMongoIndexManager <T> collection);
Exemple #15
0
 public abstract void CreateIndex(IMongoIndexManager <TEntity> indexManager);
        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);
        }
Exemple #17
0
        /// <summary>
        /// 更新索引
        /// </summary>
        /// <param name="collection">集合名</param>
        /// <param name="index">索引键</param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public string UpdateIndex(string collection, string index, bool asc = true)
        {
            IMongoIndexManager <BsonDocument> mgr = Database.GetCollection <BsonDocument>(collection).Indexes;

            return(mgr.CreateOne(asc ? Builders <BsonDocument> .IndexKeys.Ascending(doc => doc[index]) : Builders <BsonDocument> .IndexKeys.Descending(doc => doc[index])));
        }
Exemple #18
0
        /// <summary>
        /// 更新索引
        /// </summary>
        /// <param name="collection">集合名</param>
        /// <param name="key"></param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public async Task <string> UpdateIndexAsync <T>(string collection, Expression <Func <T, object> > key, bool asc = true)
        {
            IMongoIndexManager <T> mgr = Database.GetCollection <T>(collection).Indexes;

            return(await mgr.CreateOneAsync(asc?Builders <T> .IndexKeys.Ascending(key) : Builders <T> .IndexKeys.Descending(key)));
        }