Example #1
0
        // 初始化
        // parameters:
        public int Open(
            // string strMongoDbConnStr,
            MongoClient client,
            string strInstancePrefix,
            out string strError)
        {
            strError = "";

#if NO
            if (string.IsNullOrEmpty(strMongoDbConnStr) == true)
            {
                strError = "strMongoDbConnStr 参数值不应为空";
                return(-1);
            }
#endif

            if (string.IsNullOrEmpty(strInstancePrefix) == false)
            {
                strInstancePrefix = strInstancePrefix + "_";
            }

            _logDatabaseName = strInstancePrefix + "accessLog";

#if NO
            try
            {
                this._mongoClient = new MongoClient(strMongoDbConnStr);
            }
            catch (Exception ex)
            {
                strError = "初始化 MongoClient 时出错: " + ex.Message;
                return(-1);
            }
#endif

            // var server = client.GetServer();

            {
                // var db = server.GetDatabase(this._logDatabaseName);
                var db = client.GetDatabase(this._logDatabaseName);

                _logCollection = db.GetCollection <AccessLogItem>("accessLog");
                // _logCollection.DropAllIndexes();

                // if (_logCollection.GetIndexes().Count == 0)
                if (_logCollection.Indexes.List().ToList().Count == 0)
                {
#if NO
                    _logCollection.CreateIndex(new IndexKeysBuilder().Ascending("OperTime"),
                                               IndexOptions.SetUnique(false));
#endif
                    CreateIndex();
                }
            }

            _itemCount = new DailyItemCount();
            string date = GetToday();
            _itemCount.SetValue(date, GetItemCount(date));
            return(0);
        }
Example #2
0
        public EventStream(MongoDatabase database, Guid streamId)
        {
            Id = streamId;

            _collection = database.GetCollection <BsonDocument>("Commits");
            _collection.CreateIndex(IndexKeys.Ascending("StreamId", "BucketNo"), IndexOptions.SetUnique(true));
        }
Example #3
0
        private void PrepareDatabase()
        {
            _database.DropCollection(CollectionName);
            _discCollection = _database.GetCollection <Disc>(CollectionName);

            var keys    = IndexKeys.Ascending("Name", "Artist", "Year");
            var options = IndexOptions.SetUnique(true);

            _discCollection.CreateIndex(keys, options);

            _discCollection.RemoveAll();

            _disc1 = new Disc {
                Name = "Disc1", Artist = "Artist1", Gener = "Gener1", Year = "Year1"
            };
            _disc2 = new Disc {
                Name = "Disc2", Artist = "Artist2", Gener = "Gener1", Year = "Year1"
            };
            _disc3 = new Disc {
                Name = "Disc3", Artist = "Artist1", Gener = "Gener1", Year = "Year2"
            };
            _disc4 = new Disc {
                Name = "Disc4", Artist = "Artist3", Gener = "Gener2", Year = "Year2"
            };

            _discCollection.Insert(_disc1);
            _discCollection.Insert(_disc2);
            _discCollection.Insert(_disc3);
            _discCollection.Insert(_disc4);
        }
        /// <summary>
        /// 创建索引
        /// </summary>
        /// <typeparam name="T">需要创建索引的实体类型</typeparam>
        public void CreateIndex <T>()
        {
            string collectionName             = typeof(T).Name;
            MongoCollection <BsonDocument> mc = this._db.GetCollection <BsonDocument>(collectionName);

            PropertyInfo[] propertys = typeof(T).GetProperties(BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);
            //得到该实体类型的属性
            foreach (PropertyInfo property in propertys)
            {
                //在各个属性中得到其特性
                foreach (object obj in property.GetCustomAttributes(true))
                {
                    MongoAttribute mongoField = obj as MongoAttribute;
                    if (mongoField != null)                       // 此特性为mongodb的字段属性
                    {
                        IndexKeysBuilder indexKey;
                        if (mongoField.Ascending)
                        {
                            //升序 索引
                            indexKey = IndexKeys.Ascending(property.Name);
                        }
                        else
                        {
                            //降序索引
                            indexKey = IndexKeys.Ascending(property.Name);
                        }
                        //创建该属性
                        mc.CreateIndex(indexKey, IndexOptions.SetUnique(mongoField.Unique));
                    }
                }
            }
        }
        /// <summary>
        ///     Sorting by trigger time when retrieving a developer's event stream needs this index to be performant.
        /// </summary>
        private void EnsureEventChronologicalIndex()
        {
            var evtIndex = IndexKeys.Ascending(TypeExtensions <IDEEvent> .GetPropertyName(evt => evt.TriggeredAt));
            var options  = IndexOptions <IDEEvent> .SetUnique(false).SetSparse(false);

            EnsureIndex(evtIndex, options);
        }
Example #6
0
        public Post Save(string slug, Post content)
        {
            var isNew = string.IsNullOrEmpty(slug);

            if (isNew)
            {
                // No slug was specified, so we need to get the next one
                var docs = db.GetCollection("sequences");

                docs.EnsureIndex(IndexKeys.Ascending("Name"), IndexOptions.SetUnique(true));

                var sequence = docs.FindAndModify(Query.EQ("Name", "slug"), null, Update.Inc("Current", 1), true, true)
                               .GetModifiedDocumentAs <Incrementor>();

                slug = Base32Encoder.Encode(sequence.Current);
            }

            content.Slug = slug;

            content.Version = isNew ? 1 : GetLatestVersion(slug) + 1;

            db.GetCollection <Post>("posts").Save(content, SafeMode.True);

            return(content);
        }
Example #7
0
        public void TestUnique()
        {
            var    options  = IndexOptions.SetUnique(true);
            string expected = "{ \"unique\" : true }";

            Assert.AreEqual(expected, options.ToJson());
        }
 public MongoController()
 {
     objServer   = MongoServer.Create("Server=localhost:27017");
     objDatabse  = objServer.GetDatabase("UniqueTestDatabase");
     UserDetails = objDatabse.GetCollection <BsonDocument>("Users");
     UserDetails.EnsureIndex(new IndexKeysBuilder().Ascending("Name"), IndexOptions.SetUnique(true));
 }
Example #9
0
        /// <summary>
        /// Verify all required <see cref="IMongoIndexKeys"/> are defined and ready to go.
        /// </summary>
        protected virtual void VerifyIndexes <TEntity>(MongoCollection <TEntity> collection)
        {
            Type entityType = typeof(TEntity);

            if (IndexTypesByEntityType.ContainsKey(entityType))
            {
                foreach (object untypedIndexType in IndexTypesByEntityType[entityType])
                {
                    var mongoIndex = (MongoIndex <TEntity>)untypedIndexType;

                    var indexKeysBuilder = new IndexKeysBuilder();
                    if (mongoIndex.IsAcending)
                    {
                        indexKeysBuilder = indexKeysBuilder.Ascending(mongoIndex.Selectors.ToArray());
                    }
                    else
                    {
                        indexKeysBuilder = indexKeysBuilder.Descending(mongoIndex.Selectors.ToArray());
                    }

                    collection.CreateIndex
                    (
                        indexKeysBuilder,
                        IndexOptions
                        .SetUnique(mongoIndex.IsUnique)
                        .SetName(mongoIndex.Name)
                    );
                }
            }
        }
Example #10
0
        protected override void InitializeCollection(MongoCollection <Organization> collection)
        {
            base.InitializeCollection(collection);

            collection.CreateIndex(IndexKeys.Ascending(FieldNames.Invites_Token));
            collection.CreateIndex(IndexKeys.Ascending(FieldNames.Invites_EmailAddress));
            collection.CreateIndex(IndexKeys.Ascending(FieldNames.StripeCustomerId), IndexOptions.SetUnique(true).SetSparse(true));
        }
        protected override void EnsureIndexes(MongoCollection <Organization> mongoCollection)
        {
            base.EnsureIndexes(mongoCollection);

            mongoCollection.CreateIndex(
                IndexKeys <Organization> .Ascending(s => s.Name),
                IndexOptions.SetUnique(true)
                );
        }
Example #12
0
        /// <summary>
        /// Ensures that the proper indexes for GridFS exist.
        /// </summary>
        /// <param name="maxFiles">Only create new indexes if there are fewer than this number of GridFS files).</param>
        public void EnsureIndexes(
            int maxFiles
            )
        {
            // don't try to create indexes on secondaries
            var requestConnection = database.Server.RequestConnection;

            if (requestConnection != null)
            {
                // check whether the actual server instance we are using is a primary
                var serverInstance = requestConnection.ServerInstance;
                if (!serverInstance.IsPrimary)
                {
                    return;
                }
            }
            else
            {
                // check whether we are guaranteed to use a primary
                if (database.Settings.SlaveOk)
                {
                    return;
                }
            }

            // avoid round trip to count files if possible
            var indexCache = database.Server.IndexCache;

            if (
                indexCache.Contains(files, "filename_1_uploadDate_1") &&
                indexCache.Contains(chunks, "files_id_1_n_1")
                )
            {
                return;
            }

            // only create indexes if number of GridFS files is still small (to avoid performance surprises)
            var count = files.Count();

            if (count < maxFiles)
            {
                files.EnsureIndex("filename", "uploadDate");
                chunks.EnsureIndex(IndexKeys.Ascending("files_id", "n"), IndexOptions.SetUnique(true));
            }
            else
            {
                // at least check to see if the indexes exist so we can stop calling files.Count()
                if (files.IndexExistsByName("filename_1_uploadDate_1"))
                {
                    indexCache.Add(files, "filename_1_uploadDate_1");
                }
                if (chunks.IndexExistsByName("files_id_1_n_1"))
                {
                    indexCache.Add(chunks, "files_id_1_n_1");
                }
            }
        }
        /// <summary>
        ///     Events are almost unique with repsect to their session id, trigger time, and type. We need this index to enable
        ///     performant Contains checks.
        /// </summary>
        private void EnsureEventIdentityIndex()
        {
            var evtIndex = IndexKeys.Ascending(TypeExtensions <IDEEvent> .GetPropertyName(evt => evt.IDESessionUUID))
                           .Ascending(TypeExtensions <IDEEvent> .GetPropertyName(evt => evt.TriggeredAt))
                           .Ascending("_t");
            var options = IndexOptions <IDEEvent> .SetUnique(false).SetSparse(true);

            EnsureIndex(evtIndex, options);
        }
Example #14
0
        protected override void InitializeCollection(MongoCollection <User> collection)
        {
            base.InitializeCollection(collection);

            collection.EnsureIndex(IndexKeys <User> .Ascending(u => u.OrganizationIds));
            collection.EnsureIndex(IndexKeys <User> .Ascending(u => u.EmailAddress), IndexOptions.SetUnique(true));
            collection.EnsureIndex(IndexKeys.Ascending(FieldNames.OAuthAccounts_Provider, FieldNames.OAuthAccounts_ProviderUserId), IndexOptions.SetUnique(true).SetSparse(true));
            collection.EnsureIndex(IndexKeys <User> .Ascending(u => u.Roles));
        }
Example #15
0
        public MongoDbEventStore(MongoDatabase database, string eventCollectionName, bool automaticallyCreateIndexes = true)
        {
            _eventBatches = database.GetCollection <MongoEventBatch>(eventCollectionName);

            if (automaticallyCreateIndexes)
            {
                _eventBatches.CreateIndex(IndexKeys.Ascending(GlobalSeqNoDocPath), IndexOptions.SetUnique(true).SetName(GlobalSeqUniquenessIndexName));
                _eventBatches.CreateIndex(IndexKeys.Ascending(AggregateRootIdDocPath, SeqNoDocPath), IndexOptions.SetUnique(true).SetName(SeqUniquenessIndexName));
            }
        }
Example #16
0
        private void push(string iceSymbol, List <TickQuoteTw> quotes)
        {
            iceSymbol = iceSymbol.Replace(".", "_");
            foreach (TickQuoteTw quote in quotes)
            {
                MongoUtility.Instance.getCollection(symbolGroup, iceSymbol).Save <TickQuoteTw>(quote);
            }

            MongoUtility.Instance.getCollection(symbolGroup, iceSymbol).EnsureIndex(
                new IndexKeysBuilder().Ascending("datetime"), IndexOptions.SetUnique(true));
        }
Example #17
0
        public DataAccess()
        {
            _client = new MongoClient("mongodb://*****:*****@ds139436.mlab.com:39436/windowstaak");
#pragma warning disable CS0618 // Type or member is obsolete
            _server = _client.GetServer();
#pragma warning restore CS0618 // Type or member is obsolete
            _db = _server.GetDatabase("windowstaak");
            var users = _db.GetCollection <Gebruiker>("Gebruikers");

            users.CreateIndex(new IndexKeysBuilder().Ascending("Username"), IndexOptions.SetUnique(true));
        }
        public MongoDbPostRepository(IMongoConnectionFactory connectionFactory)
        {
            db = connectionFactory.Create();

            db.GetCollection("posts").EnsureIndex(
                IndexKeys.Descending("Slug", "Version"),
                IndexOptions.SetUnique(true));

            db.GetCollection("sequences").EnsureIndex(
                IndexKeys.Descending("Name"),
                IndexOptions.SetUnique(true));
        }
Example #19
0
        public virtual void CreateIndex(string[] keyNames, bool descending, bool unique)
        {
            var options = IndexOptions.SetUnique(unique);

            if (descending)
            {
                MongoDBColletion.CreateIndex(IndexKeys.Descending(keyNames), options);
            }
            else
            {
                MongoDBColletion.CreateIndex(IndexKeys.Ascending(keyNames), options);
            }
        }
Example #20
0
        public static void EnsureIndex(string connectionName, string database, string collection, MongoIndexKeysWarpper indexkeys, bool unique = false)
        {
            var mongocollection = GetCollecion(connectionName, database, collection);

            if (unique)
            {
                mongocollection.CreateIndex(indexkeys.MongoIndexKeys, IndexOptions.SetUnique(true));
            }
            else
            {
                mongocollection.CreateIndex(indexkeys.MongoIndexKeys);
            }
        }
        public PatientRepository()
        {
            _server = new MongoServer(new MongoServerSettings {
                Server = new MongoServerAddress(_DBHOST), SafeMode = SafeMode.True
            });

            //patients
            _patients = _server.GetDatabase(_DBNAME).GetCollection <PatientModel>("patients");
            _patients.EnsureIndex(IndexKeys.Ascending("_id"), IndexOptions.SetUnique(true));
            _gridFS = _server.GetDatabase(_DBNAME).GridFS;

            new MongoDB.Web.Providers.MongoDBMembershipProvider();
        }
Example #22
0
        protected void CreateUniqueIndex(string indexedField)
        {
            if (collection == null)
            {
                return;
            }

            if (collection.Count() != 0)
            {
                return;
            }

            collection.EnsureIndex(new IndexKeysBuilder().Ascending(indexedField), IndexOptions.SetUnique(true));
        }
Example #23
0
        public PostRepository(MongoDatabase mongoDatabase)
        {
            db = mongoDatabase;

            db.GetCollection("posts").EnsureIndex(
                IndexKeys.Descending("Slug", "Version"),
                IndexOptions.SetUnique(true)
                );

            db.GetCollection("sequences").EnsureIndex(
                IndexKeys.Descending("Name"),
                IndexOptions.SetUnique(true)
                );
        }
Example #24
0
        protected override void EnsureIndexes(MongoCollection <User> mongoCollection)
        {
            base.EnsureIndexes(mongoCollection);

            mongoCollection.CreateIndex(
                IndexKeys <User> .Ascending(s => s.UserName),
                IndexOptions.SetUnique(true)
                );

            mongoCollection.CreateIndex(
                IndexKeys <User> .Ascending(s => s.Email),
                IndexOptions.SetUnique(true)
                );
        }
Example #25
0
        public void Load(GameWorld world)
        {
            var db = mongoDB.DefaultDatabase;

            var tblPlayer = db.GetCollection <Player>();

            tblPlayer.EnsureIndex(IndexKeys <Player> .Ascending(p => p.Name),
                                  IndexOptions.SetUnique(true));

            var tblAccount = db.GetCollection <Account>();

            tblAccount.EnsureIndex(IndexKeys <Account> .Ascending(acc => acc.AccKey),
                                   IndexOptions.SetUnique(true));
        }
Example #26
0
        // 打开书目摘要数据库
        // parameters:
        public int OpenSummaryStorage(out string strError)
        {
            strError = "";

            if (string.IsNullOrEmpty(this.MongoDbConnStr) == true)
            {
                strError = "library.xml 中尚未配置 <mongoDB> 元素的 connectString 属性,无法打开书目摘要库";
                return(-1);
            }

            string strPrefix = this.MongoDbInstancePrefix;

            if (string.IsNullOrEmpty(strPrefix) == false)
            {
                strPrefix = strPrefix + "_";
            }

            _summaryDbName = strPrefix + "bibliosummary";

#if NO
            try
            {
                this._mongoClient = new MongoClient(this.MongoDbConnStr);
            }
            catch (Exception ex)
            {
                strError = "初始化 MongoClient 时出错: " + ExceptionUtil.GetAutoText(ex);
                return(-1);
            }
#endif
            if (this._mongoClient == null)
            {
                strError = "this._mongoClient == null";
                return(-1);
            }

            var server = this._mongoClient.GetServer();

            {
                var db = server.GetDatabase(this._summaryDbName);

                this._summaryCollection = db.GetCollection <SummaryItem>("summary");
                if (_summaryCollection.GetIndexes().Count == 0)
                {
                    _summaryCollection.CreateIndex(new IndexKeysBuilder().Ascending("BiblioRecPath"),
                                                   IndexOptions.SetUnique(true));
                }
            }
            return(0);
        }
Example #27
0
        private AspNetVirtualSiteConfig GetConfig()
        {
            var col = GetDatabase().GetCollection("AspNetVirtualSites");

            col.EnsureIndex(IndexKeys.Ascending("Name"), IndexOptions.SetUnique(true));
            var config = col.FindAs <AspNetVirtualSiteConfig>(Query.EQ("Name", VirtualSiteName)).SetLimit(1).FirstOrDefault();

            if (config == null)
            {
                throw new InvalidDataException("Virtual config for site missing: " + VirtualSiteName);
            }

            return(config);
        }
Example #28
0
        public override void CreateIndex()
        {
            _collection.CreateIndex(new IndexKeysBuilder().Ascending("OperTime"),
                                    IndexOptions.SetUnique(false));

            _collection.CreateIndex(new IndexKeysBuilder().Ascending("ItemBarcode"),
                                    IndexOptions.SetUnique(false));

            _collection.CreateIndex(new IndexKeysBuilder().Ascending("PatronBarcode"),
                                    IndexOptions.SetUnique(false));

            // 2016/1/9
            _collection.CreateIndex(new IndexKeysBuilder().Ascending("BiblioRecPath"),
                                    IndexOptions.SetUnique(false));
        }
        public void CreateIndex_SetUniqueTrue_Success()
        {
            var server     = LegacyTestConfiguration.Server;
            var database   = LegacyTestConfiguration.Database;
            var collection = database.GetCollection(GetType().Name);

            if (collection.Exists())
            {
                collection.Drop();
            }
            collection.Insert(new BsonDocument()); // make sure collection exists

            collection.CreateIndex(IndexKeys.Ascending("x"), IndexOptions.SetUnique(true));
            collection.CreateIndex(IndexKeys.Ascending("y"), IndexOptions.SetUnique(false));
        }
        public override void Setup()
        {
            base.Setup();
            Collection.EnsureIndex(
                new IndexKeysBuilder().Ascending("EMailLowercase"),
                IndexOptions.SetSparse(true).SetUnique(true));

            Collection.EnsureIndex(
                new IndexKeysBuilder().Ascending("UserNameLowercase"),
                IndexOptions.SetUnique(true));

            Collection.EnsureIndex(
                new IndexKeysBuilder().Ascending("ExternalLogins.Provider").Ascending("ExternalLogins.ProviderUserId"),
                IndexOptions.SetSparse(true).SetUnique(true));
        }