public void Bootstrap(MongoUrl mongoUrl) { var mongoClient = new MongoClient(mongoUrl); var mongoDatabase = mongoClient.GetDatabase(mongoUrl.DatabaseName); var conventionPack = new ConventionPack(); conventionPack.Add(new EnumRepresentationConvention(BsonType.String)); ConventionRegistry.Register("EnumAsString", conventionPack, f => true); BsonClassMap.RegisterClassMap <SagaStateProxy>(map => { map.SetIsRootClass(true); map.AutoMap(); map.MapIdProperty(x => x.Id).SetSerializer(new GuidSerializer(BsonType.String)); map.MapProperty(x => x.SagaId).SetSerializer(new GuidSerializer(BsonType.String)); map.MapProperty(x => x.SagaDefinitionType).SetSerializer(new TypeSerializer()); }); var mongoCollection = mongoDatabase.GetCollection <SagaStateProxy>(nameof(SagaStateProxy)); IndexKeysDefinitionBuilder <SagaStateProxy> states = new IndexKeysDefinitionBuilder <SagaStateProxy>(); var indexKeysDefinition = states.Ascending(x => x.SagaId).Descending(x => x.Version); var indexModel = new CreateIndexModel <SagaStateProxy>(indexKeysDefinition, new CreateIndexOptions() { Unique = true }); mongoCollection.Indexes.CreateOne(indexModel); }
public async Task SeedAsync() { if (await _database.Remarks().AsQueryable().AnyAsync() == false) { var index = new IndexKeysDefinitionBuilder <Remark>().Geo2DSphere(x => x.Location); await _database.Remarks().Indexes.CreateOneAsync(index); } if (await _database.Categories().AsQueryable().AnyAsync()) { return; } await _database.Categories().InsertOneAsync(new Category("defect")); await _database.Categories().InsertOneAsync(new Category("issue")); await _database.Categories().InsertOneAsync(new Category("suggestion")); await _database.Categories().InsertOneAsync(new Category("praise")); await _database.LocalizedResources().InsertOneAsync(new LocalizedResource("facebook:new_remark", "en-gb", "I've just sent a new remark using Collectively. You can see it here: {0}")); await _database.LocalizedResources().InsertOneAsync(new LocalizedResource("facebook:new_remark", "pl-pl", "Nowe zgłoszenie zostało przeze mnie dodane za pomocą Collectively. Możesz je zobaczyć tutaj: {0}")); var tags = new List <Tag> { new Tag("junk"), new Tag("small"), new Tag("medium"), new Tag("big"), new Tag("crash"), new Tag("stink"), new Tag("dirty"), new Tag("glass"), new Tag("plastic") }; await _database.Tags().InsertManyAsync(tags); }
/// <summary> /// Sets up the database indexes for collections /// </summary> private void SetupIndexes() { Log.Debug("Setting up Indexes"); IndexKeysDefinitionBuilder <Person> notificationLogBuilder = Builders <Person> .IndexKeys; IndexKeysDefinitionBuilder <Poll> pollNotificationLogBuilder = Builders <Poll> .IndexKeys; IndexKeysDefinitionBuilder <Vote> voteNotificationLogBuilder = Builders <Vote> .IndexKeys; CreateIndexModel <Person>[] indexModel = new[] { new CreateIndexModel <Person>(notificationLogBuilder.Ascending(_ => _.Passnummer)), new CreateIndexModel <Person>(notificationLogBuilder.Ascending(_ => _.Name)) }; CreateIndexModel <Poll>[] pollIndexModel = new[] { new CreateIndexModel <Poll>(pollNotificationLogBuilder.Ascending(_ => _.Id)), new CreateIndexModel <Poll>(pollNotificationLogBuilder.Ascending(_ => _.Title)) }; CreateIndexModel <Vote>[] voteIndexModel = new[] { new CreateIndexModel <Vote>(voteNotificationLogBuilder.Ascending(_ => _.Id)) }; Persons.Indexes.CreateMany(indexModel); Polls.Indexes.CreateMany(pollIndexModel); Votes.Indexes.CreateMany(voteIndexModel); Log.Debug("Index setup finished"); }
/// <summary> /// Creates all of the required MongoDB collections that this logset requires. /// </summary> protected ISet <string> CreateMongoDbCollections(ISet <string> requestedCollections, IMongoDatabase database, IParserFactory parserFactory) { IDictionary <string, ISet <string> > collectionIndexMap = BuildCollectionIndexMap(requestedCollections, parserFactory); // Create collections & indexes using the dictionary. ISet <string> collectionsCreated = new SortedSet <string>(); foreach (var collection in collectionIndexMap) { var collectionName = collection.Key; ISet <string> indexes = collection.Value; IMongoCollection <BsonDocument> dbCollection = database.GetCollection <BsonDocument>(collectionName); collectionsCreated.Add(collectionName); foreach (var index in indexes) { var indexKeysBuilder = new IndexKeysDefinitionBuilder <BsonDocument>(); CreateIndexOptions indexOptions = new CreateIndexOptions { Sparse = false }; dbCollection.Indexes.CreateOne(indexKeysBuilder.Ascending(index), indexOptions); } // If we are working against a sharded Mongo cluster, we need to explicitly shard each collection. if (mongoConnectionInfo.ConnectionType == MongoConnectionType.ShardedCluster) { MongoAdminHelper.EnableShardingOnCollectionIfNotEnabled(mongoConnectionInfo.GetClient(), database.DatabaseNamespace.DatabaseName, collectionName); } } return(collectionsCreated); }
public async void Initialize() { IMongoCollection <ModerationLogDocument> collection = DatabaseClient.Instance.MongoDatabase.GetCollection <ModerationLogDocument>(CollectionName); IndexKeysDefinitionBuilder <ModerationLogDocument> indexBuilder = Builders <ModerationLogDocument> .IndexKeys; try { CreateIndexModel <ModerationLogDocument> indexModel = new CreateIndexModel <ModerationLogDocument>(indexBuilder.Ascending(d => d.ChannelId).Ascending("Entires.Id"), new CreateIndexOptions { Name = "ModerationLogDocument_unique_ChannelId-Id", Unique = true }); _ = await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false); } catch (MongoWriteConcernException) { } try { CreateIndexModel <ModerationLogDocument> indexModel = new CreateIndexModel <ModerationLogDocument>(indexBuilder.Ascending(d => d.ChannelId).Ascending("Entires.MessageId"), new CreateIndexOptions { Name = "ModerationLogDocument_unique_ChannelId-MessageId", Unique = true }); _ = await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false); } catch (MongoWriteConcernException) { } }
public async Task SeedAsync() { if (await _database.Remarks().AsQueryable().AnyAsync() == false) { var index = new IndexKeysDefinitionBuilder <Remark>().Geo2DSphere(x => x.Location); await _database.Remarks().Indexes.CreateOneAsync(index); } if (await _database.RemarkCategories().AsQueryable().AnyAsync() == false) { var categories = await _remarkServiceClient .BrowseCategoriesAsync <RemarkCategory>(new BrowseRemarkCategories { Results = int.MaxValue }); if (categories.HasValue) { await _database.RemarkCategories().InsertManyAsync(categories.Value.Items); } } if (await _database.Tags().AsQueryable().AnyAsync() == false) { var tags = await _remarkServiceClient .BrowseTagsAsync <Models.Remarks.Tag>(new BrowseTags { Results = int.MaxValue }); if (tags.HasValue) { await _database.Tags().InsertManyAsync(tags.Value.Items); } } }
public void ApplyMultipleIndex() { var mongoClient = new MongoClient(); var modelBuilder = new ModelBuilder(mongoClient); var expected = new IndexKeysDefinitionBuilder <CustomerDocument>(); expected.Ascending(c => c.Name); modelBuilder .Document <CustomerDocument>() .DefineIndex(c => c.Ascending(x => x.Name), c => { c.Name = "Index1"; c.Unique = true; }) .DefineIndex(c => c.Ascending(x => x.Name), c => { c.Name = "Index2"; c.Unique = true; }); Assert.True(modelBuilder.Models.ContainsKey(typeof(CustomerDocument))); Assert.True(modelBuilder.Models.TryGetValue(typeof(CustomerDocument), out var configurationSource)); Assert.True(configurationSource is ConfigurationSource <CustomerDocument>); var configurationSourceTyped = (ConfigurationSource <CustomerDocument>)configurationSource; Assert.True(configurationSourceTyped.Model.Indices.Any()); Assert.True(configurationSourceTyped.Model.Indices.Count == 2); }
private async Task EnsureIndicesCreatedImplAsync() { var indexNames = new { UniqueEmail = "identity_email_unique", Login = "******" }; var pack = ConventionRegistry.Lookup(typeof(CamelCaseElementNameConvention)); var indexKeyBuilder = new IndexKeysDefinitionBuilder <TUser>(); var emailKeyBuilder = indexKeyBuilder.Ascending(user => user.Email.Value); var loginKeyBuilder = indexKeyBuilder.Ascending("logins.loginProvider").Ascending("logins.providerKey"); var tasks = new[] { _usersCollection.Indexes.CreateOneAsync(emailKeyBuilder, new CreateIndexOptions { Unique = true, Name = indexNames.UniqueEmail }), _usersCollection.Indexes.CreateOneAsync(loginKeyBuilder, new CreateIndexOptions { Name = indexNames.Login }) }; await Task.WhenAll(tasks).ConfigureAwait(false); }
public static void CreateIndices(this IApplicationBuilder app) { using (var scope = app.ApplicationServices.CreateScope()) { using (IMongoUnitOfWork unitOfWork = scope.ServiceProvider.GetService <IMongoUnitOfWork>()) { var uniqueIndexOptions = new CreateIndexOptions() { Unique = true }; IndexKeysDefinition <DefterLog> idDefinition = new IndexKeysDefinitionBuilder <DefterLog>().Descending(p => p.RequestId); var idIndexModel = new CreateIndexModel <DefterLog>(idDefinition, uniqueIndexOptions); IndexKeysDefinition <DefterLog> name = new IndexKeysDefinitionBuilder <DefterLog>() .Descending(p => p.Name); var nameIndexModel = new CreateIndexModel <DefterLog>(name); IndexKeysDefinition <DefterLog> operationName = new IndexKeysDefinitionBuilder <DefterLog>() .Descending(p => p.OperationName); var operationNameIndexModel = new CreateIndexModel <DefterLog>(operationName); unitOfWork.RepositoryManager <DefterLog>().CreateIndices(new[] { idIndexModel, nameIndexModel, operationNameIndexModel }); } } }
public bool Execute(IMongoDatabase database, MongoStorageOptions storageOptions, IMongoMigrationContext migrationContext) { var name = $@"{storageOptions.Prefix}.signal"; database.DropCollection(name); var cosmosStorageOptions = storageOptions as CosmosStorageOptions; if (cosmosStorageOptions != null) { database.CreateCollection(name); var collection = database.GetCollection <BsonDocument>(name); var options = new CreateIndexOptions { ExpireAfter = TimeSpan.FromHours(cosmosStorageOptions.CosmosHourlyTtl) }; var field = new StringFieldDefinition <BsonDocument>("_ts"); var indexDefinition = new IndexKeysDefinitionBuilder <BsonDocument>().Ascending(field); collection.Indexes.CreateOne(indexDefinition, options); } var createOptions = new CreateCollectionOptions { Capped = true, MaxSize = 1000000, MaxDocuments = 1000 }; database.CreateCollection(name, createOptions); return(true); }
public static void EnsureIndexes <T>(this IMongoCollection <T> mongoCollection) { var t = typeof(T); var indexProperties = t.GetProperties().Where(_ => Attribute.IsDefined(_, typeof(IndexedAttribute))) .Select(_ => _.Name).ToArray(); var indexes = mongoCollection.Indexes.List(); indexes.MoveNext(); var existingIndexes = indexes.Current.Select(_ => _["name"].AsString) .Where(_ => _.StartsWith(Prefix)) .Select(_ => _.Remove(0, Prefix.Length)).ToArray(); var newIndexes = indexProperties.Except(existingIndexes); var deletedIndexes = existingIndexes.Except(indexProperties); foreach (var deletedIndex in deletedIndexes) { mongoCollection.Indexes.DropOne(Prefix + deletedIndex); } foreach (var nexIndex in newIndexes) { var builder = new IndexKeysDefinitionBuilder <T>(); mongoCollection.Indexes.CreateOne(new CreateIndexModel <T>(builder.Ascending(nexIndex), new CreateIndexOptions() { Name = Prefix + nexIndex })); } }
public void createIndex(string fieldname) { var keys = new IndexKeysDefinitionBuilder <object>().Ascending(fieldname); var model = new CreateIndexModel <object>(keys); MongoCollection.Indexes.CreateOne(model); }
public DbContext(IRepositoryFactory repoFactory, string connectionString) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentNullException(nameof(connectionString)); } if (null == repoFactory) { throw new ArgumentNullException(nameof(repoFactory)); } this.Services = repoFactory.Create <Entities.Service>(new RepositoryOptions(connectionString, "services")); var servicesIxb = new IndexKeysDefinitionBuilder <Entities.Service>(); this.Services.CreateIndex(servicesIxb.Ascending(u => u.Name), new CreateIndexOptions() { Unique = true }); this.TraceEvents = repoFactory.Create <Entities.TraceEvent>(new RepositoryOptions(connectionString, "events")); var eventsIxb = new IndexKeysDefinitionBuilder <Entities.TraceEvent>(); this.TraceEvents.CreateIndex(eventsIxb.Ascending(u => u.Name), new CreateIndexOptions() { Unique = false }); }
/// <summary> /// Verify the provided <paramref name="mongoIndex"/> is defined and ready to go. /// </summary> protected virtual void VerifyIndex(MongoDbIndex <MongoDbEventData> mongoIndex) { IndexKeysDefinitionBuilder <MongoDbEventData> indexKeysBuilder = Builders <MongoDbEventData> .IndexKeys; IndexKeysDefinition <MongoDbEventData> indexKey = null; IList <Expression <Func <MongoDbEventData, object> > > selectors = mongoIndex.Selectors.ToList(); for (int i = 0; i < selectors.Count; i++) { Expression <Func <MongoDbEventData, object> > expression = selectors[i]; if (mongoIndex.IsAcending) { if (i == 0) { indexKey = indexKeysBuilder.Ascending(expression); } else { indexKey = indexKey.Ascending(expression); } } else { if (i == 0) { indexKey = indexKeysBuilder.Descending(expression); } else { indexKey = indexKey.Descending(expression); } } } bool throwExceptions; if (!bool.TryParse(ConfigurationManager.GetSetting("Cqrs.MongoDb.EventStore.ThrowExceptionsOnIndexPreparation"), out throwExceptions)) { throwExceptions = true; } try { MongoCollection.Indexes.CreateOne ( indexKey, new CreateIndexOptions { Unique = mongoIndex.IsUnique, Name = mongoIndex.Name } ); } catch { if (throwExceptions) { throw; } } }
public void CreateIndex <T>(IMongoCollection <T> collection) { var typeProperties = typeof(T).GetProperties(); foreach (var property in typeProperties) { IndexDescriptor indexDescriptor = property.GetCustomAttributes(typeof(IndexDescriptor), false).FirstOrDefault() as IndexDescriptor; if (indexDescriptor == null) { continue; } IndexKeysDefinition <T> index = null; FieldDefinition <T> indexedColumn = property.Name; switch (indexDescriptor.Type) { case IndexType.Ascending: index = new IndexKeysDefinitionBuilder <T>().Ascending(indexedColumn); break; case IndexType.Descending: index = new IndexKeysDefinitionBuilder <T>().Descending(indexedColumn); break; case IndexType.Geo2D: index = new IndexKeysDefinitionBuilder <T>().Geo2D(indexedColumn); break; case IndexType.Geo2DSphere: index = new IndexKeysDefinitionBuilder <T>().Geo2DSphere(indexedColumn); break; case IndexType.Hashed: index = new IndexKeysDefinitionBuilder <T>().Hashed(indexedColumn); break; case IndexType.Text: index = new IndexKeysDefinitionBuilder <T>().Text(indexedColumn); break; default: return; } if (index == null) { return; } var indexModel = new CreateIndexModel <T>(index, new CreateIndexOptions() { Background = indexDescriptor.Background, Sparse = indexDescriptor.Sparse, Unique = indexDescriptor.Unique }); collection.Indexes.CreateOne(indexModel); } }
/// <summary> /// Setup bucket creating Indexes /// </summary> /// <param name="bucketName">Bucket identifier</param> public async Task EnsureBucketAsync(string bucketName) { var collection = CollectionFromBucket <CommitData <T> >(bucketName); var builder = new IndexKeysDefinitionBuilder <CommitData <T> >(); // TODO Eval to use partial index for dispatched (only when dispatched is false) // https://docs.mongodb.com/manual/core/index-partial/ // This will allow us to not check for dispatched when writing and just catch the duplicate exception await collection.Indexes.CreateManyAsync(new[] { // BucketRevision is _id (automatically indexed and unique) new CreateIndexModel <CommitData <T> >(builder .Ascending(p => p.Dispatched), new CreateIndexOptions { Name = "Dispatched" }), new CreateIndexModel <CommitData <T> >(builder .Ascending(p => p.StreamId), new CreateIndexOptions { Name = "StreamId" }), new CreateIndexModel <CommitData <T> >(builder .Ascending(p => p.StreamId) .Ascending(p => p.StreamRevisionStart), new CreateIndexOptions { Name = "StreamRevision", Unique = true }) }).ConfigureAwait(false); }
/// <summary> /// Creates all of the required MongoDB collections that this logset requires. /// </summary> private void CreateMongoDbCollections() { var collections = new Dictionary <string, HashSet <string> >(); ISet <IParser> parsers = parserFactory.GetAllParsers(); // Stuff collection names & indexes into the dictionary, deduping in the process. foreach (var parser in parsers) { var collectionName = parser.CollectionSchema.CollectionName.ToLowerInvariant(); IList <string> indexes = parser.CollectionSchema.Indexes; if (!collections.ContainsKey(collectionName)) { if (LogsetDependencyHelper.IsCollectionRequiredForRequest(collectionName, logsharkRequest)) { collections.Add(collectionName, new HashSet <string>()); } } // Add indexes. if (collections.ContainsKey(collectionName)) { foreach (var index in indexes) { if (collections.ContainsKey(collectionName)) { collections[collectionName].Add(index); } } } } // New up collections & indexes using the dictionary. foreach (var collection in collections) { var collectionName = collection.Key; ISet <string> indexes = collection.Value; var dbCollection = database.GetCollection <BsonDocument>(collectionName); logsharkRequest.RunContext.CollectionsGenerated.Add(collectionName); foreach (var index in indexes) { var indexKeysBuilder = new IndexKeysDefinitionBuilder <BsonDocument>(); CreateIndexOptions indexOptions = new CreateIndexOptions { Sparse = false }; dbCollection.Indexes.CreateOne(indexKeysBuilder.Ascending(index), indexOptions); } // If we are working against a sharded Mongo cluster, we need to explicitly shard each collection. MongoConnectionInfo mongoConnectionInfo = logsharkRequest.Configuration.MongoConnectionInfo; if (mongoConnectionInfo.ConnectionType == MongoConnectionType.ShardedCluster) { MongoAdminUtil.EnableShardingOnCollectionIfNotEnabled(mongoConnectionInfo.GetClient(), logsharkRequest.RunContext.MongoDatabaseName, collectionName); } } }
/* * public UserMasterRepository() * { * var definitionBuilder = Builders<UserMaster>.IndexKeys.Combine( * Builders<UserMaster>.IndexKeys.Text(d => d.UserName), * Builders<UserMaster>.IndexKeys.Ascending(d => d.CreatedOn)); * var indexModel = new CreateIndexModel<UserMaster>(definitionBuilder); * MongoCollection.Indexes.CreateOne(indexModel); * } */ public override void CreateIndex(IndexKeysDefinitionBuilder <UserMaster> definitionBuilder) { /* * var builder = definitionBuilder.Text(d => d.UserName); * var indexModel = new CreateIndexModel<UserMaster>(builder); * await MongoCollection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false); */ }
/// <summary> /// Creates the lock indices /// </summary> /// <returns>Task</returns> public async Task CreateLockIndices() { IndexKeysDefinitionBuilder <LockEntry> lockIndexBuilder = Builders <LockEntry> .IndexKeys; CreateIndexModel <LockEntry> categoryIndex = new CreateIndexModel <LockEntry>(lockIndexBuilder.Ascending(x => x.Category)); await _LockCollection.Indexes.CreateOneAsync(categoryIndex); CreateIndexModel <LockEntry> resourceIndex = new CreateIndexModel <LockEntry>(lockIndexBuilder.Ascending(x => x.ResourceId)); await _LockCollection.Indexes.CreateOneAsync(resourceIndex); }
protected void CreateIndex(string fieldName, CreateIndexOptions options) { var field = new StringFieldDefinition <TModel>(fieldName); var indexDef = new IndexKeysDefinitionBuilder <TModel>().Ascending(field); var indexModel = new CreateIndexModel <TModel>(indexDef, options); _collection.Indexes.CreateOne(indexModel); }
public static IEnumerable <CreateIndexModel <AuditEntry> > GetIndexModel(IndexKeysDefinitionBuilder <AuditEntry> builder) { yield return(new CreateIndexModel <AuditEntry>( builder.Combine( builder.Descending(entry => entry.DateValue), builder.Ascending(entry => entry.GroupId), builder.Ascending(entry => entry.DataType) ) )); }
/// <summary> /// Adds a descending index on the field to the collection /// </summary> /// <param name="collection">The collection to add the index to</param> /// <param name="field">The field to add descending index for</param> /// <param name="name">Name of the index. Can be null, then name is auto generated</param> /// <typeparam name="TDocument"></typeparam> public static void CreateDescendingIndex <TDocument>(this IMongoCollection <TDocument> collection, Expression <Func <TDocument, object> > field, string name = null) { var builder = new IndexKeysDefinitionBuilder <TDocument>(); var options = new CreateIndexOptions <TDocument> { Name = name ?? field.GetFieldName() }; collection.Indexes.CreateOne(builder.Descending(field), options); }
public static void CreateIndex(string collectionId, string indexName) { var options = new CreateIndexOptions() { Unique = false }; var field = new StringFieldDefinition <T>(indexName); var indexDefinition = new IndexKeysDefinitionBuilder <T>().Ascending(field); database.GetCollection <T>(collectionId).Indexes.CreateOneAsync(indexDefinition, options).Wait(); }
private async void AddUniqueIndex(string property) { var options = new CreateIndexOptions() { Unique = true }; var field = new StringFieldDefinition <EngineeringTeamEntity>(property); var indexDefinition = new IndexKeysDefinitionBuilder <EngineeringTeamEntity>().Ascending(field); CreateIndexModel <EngineeringTeamEntity> _Index = new CreateIndexModel <EngineeringTeamEntity>(indexDefinition, options); await _TeamsCollection.Indexes.CreateOneAsync(_Index); }
private static void CreateIndex(DatabaseContext context) { var options = new CreateIndexOptions() { Unique = true }; var indexKeyDefinition = new IndexKeysDefinitionBuilder <PDV>().Ascending(p => p.Company.Document); var indexModel = new CreateIndexModel <PDV>(indexKeyDefinition, options); context.GetDatabase().GetCollection <PDV>(typeof(PDV).Name.ToLower()).Indexes.CreateOne(indexModel); }
/// <summary> /// Creates the timeline indices /// </summary> /// <returns>Task</returns> public async Task CreateTimelineIndices() { IndexKeysDefinitionBuilder <TimelineEntry> timelineIndexBuilder = Builders <TimelineEntry> .IndexKeys; CreateIndexModel <TimelineEntry> timelineIndex = new CreateIndexModel <TimelineEntry>(timelineIndexBuilder.Descending(x => x.Timestamp)); await _TimelineCollection.Indexes.CreateOneAsync(timelineIndex); CreateIndexModel <TimelineEntry> projectIndex = new CreateIndexModel <TimelineEntry>(timelineIndexBuilder.Ascending(x => x.ProjectId)); await _TimelineCollection.Indexes.CreateOneAsync(projectIndex); CreateIndexModel <TimelineEntry> usernameIndex = new CreateIndexModel <TimelineEntry>(timelineIndexBuilder.Ascending(x => x.Username)); await _TimelineCollection.Indexes.CreateOneAsync(usernameIndex); }
public UserDAO() { _collection = conn.getDatabase().GetCollection <UserModel>("DBUsermigration"); var options = new CreateIndexOptions() { Unique = true }; var field = new StringFieldDefinition <UserModel>("mail"); var indexDefinition = new IndexKeysDefinitionBuilder <UserModel>().Ascending(field); _collection.Indexes.CreateOneAsync(indexDefinition, options); }
private static IndexKeysDefinition <T> CreateIndexDefinition <T>(IndexKeysDefinitionBuilder <T> builder, IIndexField <T> field) { switch (field.SortOrder) { case IndexSortOrder.Desc: return(builder.Descending(field.Field)); default: case IndexSortOrder.Asc: return(builder.Ascending(field.Field)); } }
private void AddUniqueIndex(string property) { var options = new CreateIndexOptions() { Unique = true }; var field = new StringFieldDefinition <AirplaneEntity>(property); var indexDefinition = new IndexKeysDefinitionBuilder <AirplaneEntity>().Ascending(field); CreateIndexModel <AirplaneEntity> _Index = new CreateIndexModel <AirplaneEntity>(indexDefinition, options); _AirplanesCollection.Indexes.CreateOne(_Index); }
private void _createUsernameUniqueIndex() { var options = new CreateIndexOptions() { Unique = true }; var field = new StringFieldDefinition <User>("Username"); var indexDefinition = new IndexKeysDefinitionBuilder <User>().Ascending(field); var createIndexModel = new CreateIndexModel <User>(indexDefinition, options); usersCol.Indexes.CreateOne(createIndexModel); }
public async Task Stream_ExecuteCorrectOperationsInCorrectOrder() { var tailer = new Tailer(m_client); IOutlet outlet = Substitute.For<IOutlet>(); var stream = new Stream(tailer, outlet); Oplog lastOplog = await tailer.GetMostRecentOplog(); var databaseName = "_Test_MongoRiver"; var collectionName = "_Test_MongoRiver"; var newCollectionName = string.Concat(collectionName, "_foo"); var insertedDocument = new FooBarDocument { Id = "foo", Bar = "baz" }; var filterDocument = new BsonDocument("_id", "foo"); var updatedDocument = new FooBarDocument { Id = "foo", Bar = "qux" }; var indexName = "FooBar_Index"; var indexKeyDocument = new BsonDocument("Bar", 1); var indexOptionsDocument = new BsonDocument("name", indexName); IMongoDatabase database = m_client.GetDatabase(databaseName); IMongoCollection<FooBarDocument> collection = database.GetCollection<FooBarDocument>(collectionName); await collection.InsertOneAsync(insertedDocument); await collection.ReplaceOneAsync(filterDocument, updatedDocument); await collection.DeleteOneAsync(filterDocument); IndexKeysDefinition<FooBarDocument> indexDef = new IndexKeysDefinitionBuilder<FooBarDocument>().Ascending(d => d.Bar); await collection.Indexes.CreateOneAsync(indexDef, new CreateIndexOptions { Name = indexName }); await collection.Indexes.DropOneAsync(indexName); await database.RenameCollectionAsync(collectionName, newCollectionName); await database.DropCollectionAsync(newCollectionName); await m_client.DropDatabaseAsync(databaseName); await RunStream(stream, lastOplog); outlet.Received(9).UpdateOptime(Arg.Any<BsonTimestamp>()); Received.InOrder(() => { outlet.CreateCollection(databaseName, collectionName, new BsonDocument()); outlet.Insert(databaseName, collectionName, insertedDocument.ToBsonDocument()); outlet.Update(databaseName, collectionName, filterDocument, updatedDocument.ToBsonDocument()); outlet.Delete(databaseName, collectionName, filterDocument); outlet.CreateIndex(databaseName, collectionName, indexKeyDocument, indexOptionsDocument); outlet.DeleteIndex(databaseName, collectionName, indexName); outlet.RenameCollection(databaseName, collectionName, newCollectionName); outlet.DeleteCollection(databaseName, newCollectionName); outlet.DeleteDatabase(databaseName); }); }
public Authentication(string databaseUrl) { _userAccounts = DatabaseHelper.GetCollection<UserAccount>(databaseUrl); _userTokens = DatabaseHelper.GetCollection<UserToken>(databaseUrl); var index = new CreateIndexOptions { ExpireAfter = new TimeSpan(0, 30, 0, 0) }; var keysDefinitionBuilder = new IndexKeysDefinitionBuilder<UserToken>(); var indexKeysDef = keysDefinitionBuilder.Ascending(x => x.Created); _userTokens.Indexes.CreateOneAsync(indexKeysDef, index); }
public void CreateIndexes() { var client = new MongoClient(); ; var database = client.GetDatabase("test"); var collection = database.GetCollection<Student>("Users"); var indexKeysDefinition = new IndexKeysDefinitionBuilder<Student>(); Expression<Func<Student, String>> userNameExpression = x=>x.Name; var field = new ExpressionFieldDefinition<Student>(userNameExpression); //indexKeysDefinition.Ascending(); //collection.Indexes.CreateOneAsync(new IndexKeysDefinition<Student>()) }
public async void CreateSimpleUniniqueIndex() { var indexKeysDefinitionBuilder = new IndexKeysDefinitionBuilder<Student>(); Expression<Func<Student, String>> userNameExpression = x => x.Name; var field = new ExpressionFieldDefinition<Student>(userNameExpression); var ascendingIndex = indexKeysDefinitionBuilder.Ascending(field); await collection.Indexes.CreateOneAsync(ascendingIndex, new CreateIndexOptions { Name="StudentsNamesUnique", }); }
private void EnsureUniqueIndex() { var index = new IndexKeysDefinitionBuilder<WeatherAggregate>() .Ascending(wa => wa.CorrelationId); db.GetCollection<WeatherAggregate>(WeatherAggregate.Collection) .Indexes.CreateOneAsync(index, new CreateIndexOptions {Unique = true}); }