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); }
/// <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> /// 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); }
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) ) )); }
public void SetupIndexes() { Log.Debug("Setting up indexes!"); IndexKeysDefinitionBuilder <Bug> bugIndexKeysDefinition = Builders <Bug> .IndexKeys; CreateIndexModel <Bug>[] bugIndexModel = new[] { new CreateIndexModel <Bug>(bugIndexKeysDefinition.Ascending(_ => _.Id)), new CreateIndexModel <Bug>(bugIndexKeysDefinition.Ascending(_ => _.Title)) }; Bugs.Indexes.CreateMany(bugIndexModel); Log.Debug("Done setting up indexes!"); }
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 }); }
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 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 })); } }
/// <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); }
/// <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 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); }
/// <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); } } }
/// <summary> /// Adds a ascending 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 ascending 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 CreateAscendingIndex <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.Ascending(field), options); }
protected virtual void VerifyIndexes <TEntity>(IMongoCollection <TEntity> collection) { Type entityType = typeof(TEntity); if (IndexTypesByEntityType.ContainsKey(entityType)) { foreach (object untypedIndexType in IndexTypesByEntityType[entityType]) { var mongoIndex = (MongoDbIndex <TEntity>)untypedIndexType; IndexKeysDefinitionBuilder <TEntity> indexKeysBuilder = Builders <TEntity> .IndexKeys; IndexKeysDefinition <TEntity> indexKey = null; IList <Expression <Func <TEntity, object> > > selectors = mongoIndex.Selectors.ToList(); for (int i = 0; i < selectors.Count; i++) { Expression <Func <TEntity, 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); } } } collection.Indexes.CreateOne ( indexKey, new CreateIndexOptions { Unique = mongoIndex.IsUnique, Name = mongoIndex.Name } ); } } }
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)); } }
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 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 EnsureIndexesAsDeclared(EnsureIndexAttribute attribute, string indexFieldName) { var builder = new IndexKeysDefinitionBuilder <T>(); var indexKeysDefinition = attribute.Descending ? builder.Descending(indexFieldName) : builder.Ascending(indexFieldName); var createIndexOptions = new CreateIndexModel <T>(indexKeysDefinition, new CreateIndexOptions { Unique = attribute.Unique, Sparse = attribute.Sparse }); Logger.LogDebug($"Adding index on field {indexFieldName} to collection {typeof(T).Name}"); Collection.Indexes.CreateOne(createIndexOptions); }
public static IServiceCollection AddSFDataAccess(this IServiceCollection services, IConfiguration configuration) { services.AddDataAccess(configuration); DataAccessClassMap.RegisterConcreteClass <ProjectUserEntity, SFProjectUserEntity>(); services.AddMongoRepository <SFProjectEntity>(SFDataAccessConstants.ProjectsCollectionName, indexSetup: indexes => { IndexKeysDefinitionBuilder <SFProjectEntity> builder = Builders <SFProjectEntity> .IndexKeys; indexes.CreateOrUpdate(new CreateIndexModel <SFProjectEntity>(builder.Ascending("Users.Id"), new CreateIndexOptions { Unique = true })); indexes.CreateOrUpdate(new CreateIndexModel <SFProjectEntity>(builder.Ascending("Users.UserRef"))); }); services.AddMongoRepository <SyncJobEntity>("sync_jobs"); services.AddMongoRepository <TextEntity>(SFDataAccessConstants.TextsCollectionName); services.AddMongoRepository <TranslateMetrics>("translate_metrics", cm => cm.MapProperty(m => m.SessionId).SetSerializer(new StringSerializer(BsonType.ObjectId))); return(services); }
protected virtual void VerifyIndex(MongoDbIndex <EventData> mongoIndex) { IndexKeysDefinitionBuilder <EventData> indexKeysBuilder = Builders <EventData> .IndexKeys; IndexKeysDefinition <EventData> indexKey = null; IList <Expression <Func <EventData, object> > > selectors = mongoIndex.Selectors.ToList(); for (int i = 0; i < selectors.Count; i++) { Expression <Func <EventData, 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); } } } MongoCollection.Indexes.CreateOne ( indexKey, new CreateIndexOptions { Unique = mongoIndex.IsUnique, Name = mongoIndex.Name } ); }
public AnalyticsDbContext(IRepositoryFactory repoFactory, string connectionString) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentNullException(nameof(connectionString)); } if (null == repoFactory) { throw new ArgumentNullException(nameof(repoFactory)); } this.ServicesHealth = repoFactory.Create <Entities.ServiceHealth>(new RepositoryOptions(connectionString, "servicesHealth")); var servicesIxb = new IndexKeysDefinitionBuilder <Entities.ServiceHealth>(); var indexKeys = servicesIxb.Ascending(u => u.ServiceId).Ascending(u => u.TimestampMinute); this.ServicesHealth.CreateIndex(indexKeys, new CreateIndexOptions() { Unique = true }); }
protected IMongoCollection <BsonDocument> GetOrCreateMetadataCollection() { if (logsetDatabase.GetCollection <BsonDocument>(CoreConstants.MONGO_METADATA_COLLECTION_NAME).Indexes.List().ToList().Count == 0) { return(logsetDatabase.GetCollection <BsonDocument>(CoreConstants.MONGO_METADATA_COLLECTION_NAME)); } Log.DebugFormat("Creating '{0}' collection in Mongo database '{1}'..", CoreConstants.MONGO_METADATA_COLLECTION_NAME, logsharkRequest.RunContext.MongoDatabaseName); var collection = logsetDatabase.GetCollection <BsonDocument>(CoreConstants.MONGO_METADATA_COLLECTION_NAME); foreach (var index in CoreConstants.MONGO_METADATA_COLLECTION_INDEXES) { var indexKeysBuilder = new IndexKeysDefinitionBuilder <BsonDocument>(); CreateIndexOptions indexOptions = new CreateIndexOptions { Sparse = false }; collection.Indexes.CreateOne(indexKeysBuilder.Ascending(index), indexOptions); } return(collection); }
static private void CreateUniqueIndex <TDocument>(IMongoCollection <TDocument> collection, string indexName, params string[] fieldNames) { List <BsonDocument> list = collection.Indexes.List().ToList <BsonDocument>(); if (list.Find(index => index["name"] == indexName) == null) { IndexKeysDefinition <TDocument> indexDefinition = new IndexKeysDefinitionBuilder <TDocument>().Ascending(new StringFieldDefinition <TDocument>(fieldNames[0])); CreateIndexOptions options = new CreateIndexOptions() { Name = indexName, Unique = true }; for (int i = 1; i < fieldNames.Length; i++) { string fieldName = fieldNames[i]; StringFieldDefinition <TDocument> field = new StringFieldDefinition <TDocument>(fieldName); indexDefinition = indexDefinition.Ascending(field); } collection.Indexes.CreateOneAsync(indexDefinition, options); } }
/// <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); }
public async void Initialize() { IMongoCollection <PluginDocument> collection = DatabaseClient.Instance.MongoDatabase.GetCollection <PluginDocument>(CollectionName); IndexKeysDefinitionBuilder <PluginDocument> indexBuilder = Builders <PluginDocument> .IndexKeys; try { CreateIndexModel <PluginDocument> indexModel = new CreateIndexModel <PluginDocument>(indexBuilder.Ascending(d => d.EnabledChannelIds), new CreateIndexOptions { Name = "PluginDocument_unique_EnabledChannelIds", Unique = true }); _ = await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false); } catch (MongoWriteConcernException) { } }
/// <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 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 void Initialize() { IMongoCollection <UserDocument> collection = DatabaseClient.Instance.MongoDatabase.GetCollection <UserDocument>(CollectionName); IndexKeysDefinitionBuilder <UserDocument> indexBuilder = Builders <UserDocument> .IndexKeys; try { CreateIndexModel <UserDocument> indexModel = new CreateIndexModel <UserDocument>(indexBuilder.Ascending(d => d.Login), new CreateIndexOptions { Name = "UserDocument_unique_Login", Unique = true }); _ = await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false); } catch (MongoWriteConcernException) { } try { CreateIndexModel <UserDocument> indexModel = new CreateIndexModel <UserDocument>(indexBuilder.Ascending(d => d.Id), new CreateIndexOptions { Name = "UserDocument_unique_Id", Unique = true }); _ = await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false); } catch (MongoWriteConcernException) { } try { CreateIndexModel <UserDocument> indexModel = new CreateIndexModel <UserDocument>(indexBuilder.Combine(indexBuilder.Ascending(d => d.Id), indexBuilder.Ascending(d => d.PermissionGroupMembership)), new CreateIndexOptions { Name = "UserDocument_unique_PermissionGroupMembership", Unique = true }); _ = await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false); } catch (MongoWriteConcernException) { } }