public void EnsureIndex_SetUniqueTrue_Success() { var server = MongoServer.Create("mongodb://localhost/?safe=true"); var database = server["onlinetests"]; var collection = database.GetCollection("csharp93"); if (collection.Exists()) { collection.DropAllIndexes(); } else { collection.Insert(new BsonDocument()); // make sure collection exists } collection.EnsureIndex(IndexKeys.Ascending("x"), IndexOptions.SetUnique(true)); collection.EnsureIndex(IndexKeys.Ascending("y"), IndexOptions.SetUnique(false)); }
public void EnsureIndex_SetUniqueTrue_Success() { var server = Configuration.TestServer; var database = Configuration.TestDatabase; var collection = Configuration.TestCollection; if (collection.Exists()) { collection.DropAllIndexes(); } else { collection.Insert(new BsonDocument()); // make sure collection exists } collection.EnsureIndex(IndexKeys.Ascending("x"), IndexOptions.SetUnique(true)); collection.EnsureIndex(IndexKeys.Ascending("y"), IndexOptions.SetUnique(false)); }
protected override async Task SetupCollectionAsync(IMongoCollection <UserNotification> collection, CancellationToken ct) { await Collection.Indexes.CreateOneAsync( new CreateIndexModel <UserNotification>( IndexKeys .Ascending(x => x.UserId) .Ascending(x => x.EventId)), null, ct); await Collection.Indexes.CreateOneAsync( new CreateIndexModel <UserNotification>( IndexKeys .Ascending(x => x.AppId) .Ascending(x => x.UserId) .Ascending(x => x.Updated) .Descending(x => x.Created)), null, ct); }
public override void createIndex(MongodbHelper db, string url) { MongoDatabase mdb = db.MongoDb; if (mdb == null) { return; } try { var table = mdb.GetCollection(TableName.OPLOG); table.CreateIndex(IndexKeys.Ascending("OpType"), IndexOptions.SetBackground(true)); } catch (System.Exception ex) { } }
/// <summary> /// 创建索引 /// </summary> /// <typeparam name="T">需要创建索引的实体类型</typeparam> public bool CreateIndex <T>() { if (this._db == null) { return(false); } try { 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)) { MongoFieldAttribute mongoField = obj as MongoFieldAttribute; if (mongoField != null) {// 此特性为mongodb的字段属性 IndexKeysBuilder indexKey; if (mongoField.Ascending) { //升序 索引 indexKey = IndexKeys.Ascending(property.Name); } else { //降序索引 indexKey = IndexKeys.Descending(property.Name); } //创建该属性 mc.CreateIndex(indexKey, IndexOptions.SetUnique(mongoField.Unique)); } } } return(true); } catch (Exception ex) { return(false); } }
private static void Seo(MongoDatabase database) { var seoCollection = database.GetCollection("site.seo"); var seoIndexes = seoCollection.GetIndexes(); if (seoIndexes.All(c => c.Name != "Url")) { var keys = IndexKeys.Ascending("Url"); var options = IndexOptions.SetName("Url"); seoCollection.CreateIndex(keys, options); } if (seoIndexes.All(c => c.Name != "SiteId")) { var keys = IndexKeys.Ascending("SiteId"); var options = IndexOptions.SetName("SiteId"); seoCollection.CreateIndex(keys, options); } }
public MongoDataProvider(string joinParentId, string mongoConnectionString, string databaseName, string safeMode) { bool parsedSafeMode; SafeMode = SafeMode.Create(bool.TryParse(safeMode, out parsedSafeMode) ? parsedSafeMode : false); JoinParentId = new ID(joinParentId); Server = MongoServer.Create(mongoConnectionString); Db = Server.GetDatabase(databaseName); Items = Db.GetCollection <Item>("items", SafeMode); Items.EnsureIndex(IndexKeys.Ascending(new[] { "ParentID" })); Items.EnsureIndex(IndexKeys.Ascending(new[] { "TemplateID" })); EnsureNotEmpty(); }
protected override async Task SetupCollectionAsync(IMongoCollection <MongoEventCommit> collection) { var indexNames = await Task.WhenAll( collection.Indexes.CreateOneAsync(IndexKeys.Ascending(x => x.EventsOffset), new CreateIndexOptions { Unique = true }), collection.Indexes.CreateOneAsync(IndexKeys.Ascending(x => x.EventStreamOffset).Ascending(x => x.EventStream), new CreateIndexOptions { Unique = true }), collection.Indexes.CreateOneAsync(IndexKeys.Descending(x => x.EventsOffset), new CreateIndexOptions { Unique = true }), collection.Indexes.CreateOneAsync(IndexKeys.Descending(x => x.EventStreamOffset).Ascending(x => x.EventStream), new CreateIndexOptions { Unique = true })); eventsOffsetIndex = indexNames[0]; }
private static void Cache(MongoDatabase database) { var cacheCollection = database.GetCollection("site.cache"); var cacheIndexes = cacheCollection.GetIndexes(); if (cacheIndexes.All(c => c.Name != "SiteId")) { var keys = IndexKeys.Ascending("SiteId"); var options = IndexOptions.SetName("SiteId"); cacheCollection.CreateIndex(keys, options); } if (cacheIndexes.All(c => c.Name != "ParentId")) { var keys = IndexKeys.Ascending("Key", "Type"); var options = IndexOptions.SetName("KeyType"); cacheCollection.CreateIndex(keys, options); } }
public void Verify_create_index_different_options_no_name() { _sut.CreateIndex( IndexKeys <SampleReadModel> .Ascending(x => x.Timestamp), IndexOptions.SetUnique(false)); //now modify the index, should not throw _sut.CreateIndex( IndexKeys <SampleReadModel> .Ascending(x => x.Timestamp), IndexOptions.SetUnique(true)); var index = _collection.GetIndexes().Single(x => x.Name == "Timestamp_1"); Assert.That(index.Name, Is.EqualTo("Timestamp_1")); Assert.That(index.Key["Timestamp"].AsInt32, Is.EqualTo(1)); Assert.That(index.IsUnique, Is.True); }
private static void Items(MongoDatabase database) { var itemsCollection = database.GetCollection("site.item"); var itemIndexes = itemsCollection.GetIndexes(); if (itemIndexes.All(c => c.Name != "SiteId")) { var keys = IndexKeys.Ascending("SiteId"); var options = IndexOptions.SetName("SiteId"); itemsCollection.CreateIndex(keys, options); } if (itemIndexes.All(c => c.Name != "ParentId")) { var keys = IndexKeys.Ascending("SiteId", "ParentId"); var options = IndexOptions.SetName("ParentId"); itemsCollection.CreateIndex(keys, options); } }
private static void Stats(MongoDatabase database) { var statsCollection = database.GetCollection("site.stats"); var statIndexes = statsCollection.GetIndexes(); if (statIndexes.All(c => c.Name != "SiteId")) { var keys = IndexKeys.Ascending("SiteId"); var options = IndexOptions.SetName("SiteId"); statsCollection.CreateIndex(keys, options); } if (statIndexes.All(c => c.Name != "CreateDate")) { var keys = IndexKeys.Ascending("CreateDate"); var options = IndexOptions.SetName("CreateDate"); statsCollection.CreateIndex(keys, options); } }
/// <summary> /// Initializes database. This is not fast, so avoid calling it constantly. Ideally, this method is called /// when your app starts up. /// </summary> public void InitializeDatabase() { MongoDefine instance = MongoTypeProvider.GetDefinition(); IEnumerable <MCollection> collections = instance.Define(); foreach (MCollection collection in collections) { if (!_mongo.CollectionExists(collection.Name)) { _mongo.CreateCollection(collection.Name); } // set up indexes if (collection.Indices.Length > 0) { _mongo.GetCollection <BsonDocument>(collection.Name).CreateIndex(IndexKeys.Ascending(collection.Indices), IndexOptions.SetUnique(true)); } } }
public static EventStream OpenExistingStream(MongoDatabase database, Guid streamId) { var collection = database.GetCollection <BsonDocument>("Commits"); collection.CreateIndex(IndexKeys.Ascending("StreamId", "BucketNo"), IndexOptions.SetUnique(true)); var document = LoadStreamHeader(collection, streamId); if (document == null) { return(null); } var revision = document["StreamRevision"].AsInt32; var bucketNo = document["BucketNo"].AsInt32; var bucketSize = document["BucketSize"].AsInt32; return(new EventStream(collection, streamId, revision, bucketNo, bucketSize)); }
public override void createIndex(MongodbHelper db, string url) { MongoDatabase mdb = db.MongoDb; if (mdb == null) { return; } if (url == WebConfigurationManager.AppSettings["account"]) { return; } var table = mdb.GetCollection(TableName.PLAYER_INFO); table.CreateIndex(IndexKeys.Ascending("gold"), IndexOptions.SetBackground(true)); table.CreateIndex(IndexKeys.Ascending("ticket"), IndexOptions.SetBackground(true)); }
protected override async Task SetupCollectionAsync(IMongoCollection <MongoDbApp> collection, CancellationToken ct) { await collection.Indexes.CreateOneAsync( new CreateIndexModel <MongoDbApp>( IndexKeys .Ascending(x => x.Doc.EmailVerificationStatus)), null, ct); await collection.Indexes.CreateOneAsync( new CreateIndexModel <MongoDbApp>( IndexKeys .Ascending(x => x.Doc.EmailAddress)), null, ct); await collection.Indexes.CreateOneAsync( new CreateIndexModel <MongoDbApp>( IndexKeys .Ascending(x => x.ContributorIds)), null, ct); }
public void Verify_create_index_change_fields() { _sut.CreateIndex( IndexKeys <SampleReadModel> .Ascending(x => x.Timestamp), IndexOptions.SetName("TestIndex")); //now modify the index, should not throw _sut.CreateIndex( IndexKeys <SampleReadModel> .Ascending(x => x.Timestamp) .Descending(x => x.IsInRebuild), IndexOptions.SetName("TestIndex")); var index = _collection.GetIndexes().Single(x => x.Name == "TestIndex"); Assert.That(index.Name, Is.EqualTo("TestIndex")); Assert.That(index.Key["Timestamp"].AsInt32, Is.EqualTo(1)); Assert.That(index.Key["IsInRebuild"].AsInt32, Is.EqualTo(-1)); }
private MongoCollection <BsonDocument> GetMongoCollection() { MongoCollection <BsonDocument> collection; if (_collectionDict.TryGetValue(UsernameCollectionName, out collection)) { return(collection); } lock (this) { var client = new MongoClient(ConnectionString); var db = client.GetServer().GetDatabase(new MongoUrl(ConnectionString).DatabaseName); collection = db.GetCollection(UsernameCollectionName); collection.EnsureIndex(IndexKeys.Ascending("UserName"), IndexOptions.SetName("UserNameUniqueIndex").SetUnique(true)); _collectionDict.TryAdd(UsernameCollectionName, collection); } return(collection); }
/// <summary> /// Ensures that the desired unique index exists on one or multiple properties, and creates it if it does not. /// </summary> /// <param name="collection"></param> /// <param name="fieldExpression"></param> public static void EnsureUniqueIndex <T>(this MongoCollection <T> collection, params Expression <Func <T, object> >[] fieldExpression) where T : class { var propNames = new List <string>(); var counter = 1; foreach (var pi in fieldExpression.Select(GetPropertyInfo)) { if (pi == null) { throw new InvalidOperationException(string.Format("Expression {0} must be a property reference", counter)); } propNames.Add(pi.Name); counter++; } collection.EnsureIndex(IndexKeys.Ascending(propNames.ToArray()), IndexOptions.SetUnique(true)); }
/// <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) { // EnsureIndexes should only be called for update operations // read-only operations shouldn't call EnsureIndexes because: // 1. we might be reading from a secondary // 2. we might be authenticating as a read-only uaser var database = GetDatabase(ReadPreference.Primary); var filesCollection = GetFilesCollection(database); var chunksCollection = GetChunksCollection(database); // only create indexes if number of GridFS files is still small (to avoid performance surprises) var count = filesCollection.Count(); if (count < maxFiles) { filesCollection.CreateIndex("filename", "uploadDate"); chunksCollection.CreateIndex(IndexKeys.Ascending("files_id", "n"), IndexOptions.SetUnique(true)); } }
protected override async Task SetupCollectionAsync(IMongoCollection <MongoDbEvent> collection, CancellationToken ct) { await Collection.Indexes.CreateOneAsync( new CreateIndexModel <MongoDbEvent>( IndexKeys .Ascending(x => x.Doc.AppId) .Ascending(x => x.Doc.Topic) .Ascending(x => x.SearchText) .Descending(x => x.Doc.Created)), null, ct); await Collection.Indexes.CreateOneAsync( new CreateIndexModel <MongoDbEvent>( IndexKeys .Descending(x => x.Doc.Created), new CreateIndexOptions { ExpireAfter = TimeSpan.FromDays(10) }), null, ct); }
protected override async Task SetupCollectionAsync(IMongoCollection <MongoDbUser> collection, CancellationToken ct) { await collection.Indexes.CreateOneAsync( new CreateIndexModel <MongoDbUser>( IndexKeys .Ascending(x => x.Doc.AppId) .Ascending(x => x.Doc.FullName) .Ascending(x => x.Doc.EmailAddress), null), null, ct); await collection.Indexes.CreateOneAsync( new CreateIndexModel <MongoDbUser>( IndexKeys .Ascending(x => x.Doc.ApiKey), new CreateIndexOptions { Unique = true }), null, ct); }
/// <summary> /// create index /// </summary> /// <typeparam name="T">data type</typeparam> /// <param name="indexKeys">fields for index</param> public void CreateIndex <T>(string[] indexKeys, bool unique) where T : class, new() { if (indexKeys.Length > 0) { var keys = IndexKeys.Ascending(indexKeys); var options = IndexOptions.SetUnique(unique); StringBuilder indexName = new StringBuilder(); indexName.Append("Index"); foreach (string key in indexKeys) { indexName.AppendFormat("_{0}", key); } options.SetName(indexName.ToString()); this.GetCollection <T>().CreateIndex(keys, options); } }
public Task CreateCollectionIfNotExist(string route) { var collectionName = _mongoAgent.GetEnvelopsCollectionName(route); var db = _mongoAgent.GetDb(); if (!db.CollectionExists(collectionName)) { var collectionOptionsBuilder = new CollectionOptionsBuilder() .SetCapped(true) .SetMaxDocuments(1000000) .SetMaxSize(500000000); db.CreateCollection(collectionName, collectionOptionsBuilder); var collection = db.GetCollection(collectionName); collection.CreateIndex(IndexKeys <Envelope> .Ascending(x => x.IsRead)); collection.CreateIndex(IndexKeys <Envelope> .Descending(x => x.ReadAt).Ascending(x => x.ProcessedAt)); collection.CreateIndex(IndexKeys <Envelope> .Descending(x => x.ProcessingStartedAt).Ascending(x => x.ProcessedAt)); collection.CreateIndex(IndexKeys <Envelope> .Descending(x => x.Id).Ascending(x => x.ProcessedAt)); } return(Task.FromResult(true)); }
public void TestDropAllIndexes() { var server = LegacyTestConfiguration.Server; var database = LegacyTestConfiguration.Database; var collection = LegacyTestConfiguration.Collection; if (collection.Exists()) { collection.DropAllIndexes(); } else { collection.Insert(new BsonDocument()); // make sure collection exists } collection.CreateIndex("x", "y"); collection.DropIndex("x", "y"); collection.CreateIndex(IndexKeys.Ascending("x", "y")); collection.DropIndex(IndexKeys.Ascending("x", "y")); }
protected override async Task SetupCollectionAsync(IMongoCollection <MongoDbSubscription> collection, CancellationToken ct) { await collection.Indexes.CreateOneAsync( new CreateIndexModel <MongoDbSubscription>( IndexKeys .Ascending(x => x.AppId) .Ascending(x => x.UserId) .Ascending(x => x.TopicArray)), null, ct); await collection.Indexes.CreateOneAsync( new CreateIndexModel <MongoDbSubscription>( IndexKeys .Ascending(x => x.AppId) .Ascending(x => x.TopicPrefix) .Ascending(x => x.UserId), new CreateIndexOptions { Unique = true }), null, ct); }
public override void createIndex(MongodbHelper db, string url) { MongoDatabase mdb = db.MongoDb; if (mdb == null) { return; } try { var table = mdb.GetCollection(TableName.PUMP_PLAYER_MONEY); table.CreateIndex(IndexKeys.Ascending("playerId"), IndexOptions.SetBackground(true)); table.CreateIndex(IndexKeys.Ascending("gameId"), IndexOptions.SetBackground(true)); table.CreateIndex(IndexKeys.Ascending("itemId"), IndexOptions.SetBackground(true)); table.CreateIndex(IndexKeys.Ascending("reason"), IndexOptions.SetBackground(true)); } catch (System.Exception ex) { } }
public static void Main(string[] args) { var server = MongoServer.Create("mongodb://localhost/?safe=true"); var database = server["test"]; var users = database.GetCollection <User>("users"); if (users.Exists()) { users.Drop(); } users.EnsureIndex(IndexKeys.Ascending("EmailAddress"), IndexOptions.SetUnique(true)); var john = new User { FirstName = "John", LastName = "Smith", EmailAddress = "*****@*****.**" }; users.Insert(john); var joe = new User { FirstName = "Joe", LastName = "Smith", EmailAddress = "*****@*****.**" }; users.Insert(joe); // should throw exception }
public void CreateIndex_DropIndex_Test() { const string CollectionName = "create-index-drop-index-test"; Repository.DropCollection(CollectionName); Repository.CreateCollection(CollectionName); Repository.Insert(new BsonDocument()); Repository.DropAllIndexes(); var indexes = Repository.GetIndexes().ToArray(); indexes.Length.Should().Be(1); indexes[0].RawDocument["name"].AsString.Should().Be(MongoTool.IdIndexName); indexes[0].RawDocument["name"].AsString.Should().Be(MongoTool.IdIndexName); Repository.CreateIndex("x"); indexes = Repository.GetIndexes().ToArray(); indexes.Length.Should().Be(2); indexes[0].RawDocument["name"].AsString.Should().Be(MongoTool.IdIndexName); indexes[1].RawDocument["name"].AsString.Should().Be("x_1"); Repository.DropIndexByName("x_1"); indexes = Repository.GetIndexes().ToArray(); indexes.Length.Should().Be(1); indexes[0].RawDocument["name"].AsString.Should().Be(MongoTool.IdIndexName); Repository.CreateIndex(IndexKeys.Ascending("x").Descending("y"), IndexOptions.SetUnique(true)); indexes = Repository.GetIndexes().ToArray(); indexes.Length.Should().Be(2); indexes[0].RawDocument["name"].AsString.Should().Be(MongoTool.IdIndexName); indexes[1].RawDocument["name"].AsString.Should().Be("x_1_y_-1"); indexes[1].RawDocument["unique"].ToBoolean().Should().Be.True(); Repository.DropAllIndexes(); Repository.DropCollection(CollectionName); }
public void TestCreateIndex() { collection.DropAllIndexes(); var indexes = collection.GetIndexes().ToArray(); Assert.AreEqual(1, indexes.Length); Assert.AreEqual("_id_", indexes[0]["name"].AsString); collection.DropAllIndexes(); collection.CreateIndex("x"); indexes = collection.GetIndexes().ToArray(); Assert.AreEqual(2, indexes.Length); Assert.AreEqual("_id_", indexes[0]["name"].AsString); Assert.AreEqual("x_1", indexes[1]["name"].AsString); collection.DropAllIndexes(); collection.CreateIndex(IndexKeys.Ascending("x").Descending("y"), IndexOptions.SetUnique(true)); indexes = collection.GetIndexes().ToArray(); Assert.AreEqual(2, indexes.Length); Assert.AreEqual("_id_", indexes[0]["name"].AsString); Assert.AreEqual("x_1_y_-1", indexes[1]["name"].AsString); Assert.AreEqual(true, indexes[1]["unique"].ToBoolean()); }