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 void CreateIndex_SetUniqueTrue_Success() { 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(IndexKeys.Ascending("x"), IndexOptions.SetUnique(true)); collection.CreateIndex(IndexKeys.Ascending("y"), IndexOptions.SetUnique(false)); }
public void Handle(CurrenciesCreated message) { BsonDocument ccy = BsonDocument.Parse(message.CurrenciesCreatedJson); BsonDocument index = new BsonDocument(); index["_id"] = ccy["_id"]; index["Name"] = ccy["Name"]; index["Code"] = ccy["Code"]; index["OwnerId"] = ccy["OwnerId"]; index["Keywords"] = BsonValue.Create(new string[] { ccy["_id"].ToString(), ccy["Name"].ToString(), ccy["Code"].ToString(), ccy["OwnerId"].ToString() }); Collections.Save(index); Collections.EnsureIndex(IndexKeys.Descending("Keywords"), IndexOptions.SetName("Keywords")); }
public void CreateIndex_with_wildcardProjection_should_create_expected_index() { RequireServer.Check().Supports(Feature.WildcardIndexes); var collection = _database.GetCollection <BsonDocument>("test_wildcard_index"); collection.Drop(); collection.CreateIndex( IndexKeys.Wildcard(), // wildcardProjection can be only with '$**' IndexOptions .SetWildcardProjection("_id", true) .SetName("custom")); var indexes = collection.GetIndexes(); var index = indexes.RawDocuments.Single(i => i["name"].AsString == "custom"); index["key"]["$**"].AsInt32.Should().Be(1); index["wildcardProjection"].Should().Be(BsonDocument.Parse("{ _id : 1 }")); }
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 TestSetHint() { collection.DropAllIndexes(); collection.RemoveAll(); collection.Insert(new BsonDocument { { "x", 1 }, { "y", 2 } }); collection.CreateIndex(IndexKeys.Ascending("x")); var query = Query.EQ("x", 1); var cursor = collection.Find(query).SetHint(new BsonDocument("x", 1)); var count = 0; foreach (var document in cursor) { Assert.AreEqual(1, ++count); Assert.AreEqual(1, document["x"].AsInt32); } }
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) { } }
public void CreateIndex_with_wildcardProjection_should_create_expected_index() { RequireServer.Check().Supports(Feature.WildcardIndexes); var collection = _database.GetCollection <Test>("test_wildcard_index"); collection.Drop(); collection.CreateIndex( IndexKeys <Test> .Wildcard(), IndexOptions <Test> .SetName("custom") .SetWildcardProjection(c => c.B, true) .SetWildcardProjection(c => c.Id, false)); var indexes = collection.GetIndexes(); var index = indexes.RawDocuments.Single(i => i["name"].AsString == "custom"); index["key"]["$**"].AsInt32.Should().Be(1); index["wildcardProjection"].ToBsonDocument().Should().Be(BsonDocument.Parse("{ b : 1, _id : 0 }")); }
public void TestMetaText() { if (LegacyTestConfiguration.Server.Primary.Supports(FeatureId.TextSearchQuery)) { var collection = LegacyTestConfiguration.Database.GetCollection <BsonDocument>("test_meta_text_sort"); collection.Drop(); collection.CreateIndex(IndexKeys.Text("textfield")); collection.Insert(new BsonDocument { { "_id", 1 }, { "textfield", "The quick brown fox jumped" }, { "z", 1 } }); collection.Insert(new BsonDocument { { "_id", 2 }, { "textfield", "over the lazy brown dog and brown cat" }, { "z", 2 } }); collection.Insert(new BsonDocument { { "_id", 3 }, { "textfield", "over the lazy brown dog and brown cat" }, { "z", 4 } }); collection.Insert(new BsonDocument { { "_id", 4 }, { "textfield", "over the lazy brown dog and brown cat" }, { "z", 3 } }); var query = Query.Text("brown"); var fields = Fields.MetaTextScore("relevance"); var sortBy = SortBy.MetaTextScore("relevance").Descending("z"); var cursor = collection.FindAs <BsonDocument>(query).SetFields(fields).SetSortOrder(sortBy); var result = cursor.ToArray(); Assert.Equal(4, result.Length); Assert.Equal(3, result[0]["_id"].AsInt32); Assert.Equal(4, result[1]["_id"].AsInt32); Assert.Equal(2, result[2]["_id"].AsInt32); Assert.Equal(1, result[3]["_id"].AsInt32); } }
/// <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); } }
/// <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)); } } }
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); } }
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)); }
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); }
public void Handle(TaxCreated message) { BsonDocument tax = BsonDocument.Parse(message.TaxJson); BsonDocument index = new BsonDocument(); index["_id"] = tax["_id"]; index["Name"] = tax["Name"]; index["Value"] = tax["Value"]; index["OwnerId"] = tax["OwnerId"]; index["Keywords"] = BsonValue.Create(new string[4] { tax["_id"].ToString(), tax["Name"].ToString(), tax["Value"].ToString(), tax["OwnerId"].ToString() }); Collections.Save(index); Collections.EnsureIndex(IndexKeys.Descending("Keywords"), IndexOptions.SetName("Keywords")); }
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 TestMetaText() { var server = Configuration.TestServer; var primary = server.Primary; if (primary.Supports(FeatureId.TextSearchQuery)) { using (server.RequestStart(null, primary)) { var collection = Configuration.TestDatabase.GetCollection <TestClass>("test_meta_text"); collection.Drop(); collection.CreateIndex(IndexKeys <TestClass> .Text(x => x.textfield)); collection.Insert(new TestClass { _id = 1, textfield = "The quick brown fox jumped", x = 1 }); collection.Insert(new TestClass { _id = 2, textfield = "over the lazy brown dog", x = 1 }); var query = Query.Text("fox"); var result = collection.FindOneAs <BsonDocument>(query); Assert.AreEqual(1, result["_id"].AsInt32); Assert.IsFalse(result.Contains("relevance")); Assert.IsTrue(result.Contains("x")); var fields = Fields <TestClass> .MetaTextScore(y => y.relevance).Exclude(y => y.x); result = collection.FindOneAs <BsonDocument>(new FindOneArgs() { Query = query, Fields = fields }); Assert.AreEqual(1, result["_id"].AsInt32); Assert.IsTrue(result.Contains("relevance")); Assert.IsFalse(result.Contains("x")); } } }
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]; }
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 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(); }
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); } }
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); } }
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); }
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); }
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)); }
/// <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 <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 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)); }