public bool CollectionExists(string collectionName) { var filter = new BsonDocument("name", collectionName); var options = new ListCollectionNamesOptions { Filter = filter }; return(database.ListCollectionNames(options).Any()); }
private bool CollectionExists() { var filter = new BsonDocument("name", _collectionName); var options = new ListCollectionNamesOptions { Filter = filter }; return(_database.ListCollectionNames(options).Any()); }
public static async Task <bool> CollectionExistsAsync(this IMongoDatabase database, string collectionName) { var options = new ListCollectionNamesOptions { Filter = new BsonDocument("name", collectionName) }; return((await database.ListCollectionNamesAsync(options)).Any()); }
private bool CheckIfCollectionExists(IMongoDatabase database, string collectionName) { var nameFilter = new BsonDocument("name", collectionName); var options = new ListCollectionNamesOptions { Filter = nameFilter }; return(database.ListCollectionNames(options).Any()); }
private bool TableExists(string _TableName) { var filter = new BsonDocument("name", _TableName); var options = new ListCollectionNamesOptions { Filter = filter }; return(MongoDB.ListCollectionNames(options).Any()); }
public static IMongoCollection <T> CriarCollection <T>(this IMongoDatabase database) { var filtro = new ListCollectionNamesOptions { Filter = Builders <BsonDocument> .Filter.Eq("name", typeof(T).Name) }; if (!database.ListCollectionNames(filtro).Any()) { database.CreateCollection(typeof(T).Name); } return(database.GetCollection <T>(typeof(T).Name)); }
public static async Task <bool> CollectionExistsAsync(this IMongoDatabase database, string collectionName, CancellationToken ct = default) { var options = new ListCollectionNamesOptions { Filter = new BsonDocument("name", collectionName) }; var collections = await database.ListCollectionNamesAsync(options, ct); return(await collections.AnyAsync(ct)); }
// <summary> /// Initializes the collection and the unique indexes. /// </summary> private void CreateCollectionIfNeeded() { var productFilter = new ListCollectionNamesOptions { Filter = Builders <BsonDocument> .Filter.Eq("name", CollectionName) }; if (!MongoDatabase.ListCollectionNames(_session, productFilter).Any()) { MongoDatabase.CreateCollection(_session, CollectionName); } }
protected virtual void CreateCollectionIfNotExists(AbpMongoDbContext dbContext, string collectionName) { var filter = new BsonDocument("name", collectionName); var options = new ListCollectionNamesOptions { Filter = filter }; if (!dbContext.Database.ListCollectionNames(options).Any()) { dbContext.Database.CreateCollection(collectionName); } }
private IMongoCollection <MessageOutboxEntity> CreateCollectionIfNotExists(IMongoDatabase database, string collectionName) { var filter = new BsonDocument("name", collectionName); var options = new ListCollectionNamesOptions { Filter = filter }; if (!database.ListCollectionNames(options).Any()) { database.CreateCollection(collectionName); } return(database.GetCollection <MessageOutboxEntity>(collectionName)); }
private static async Task <DeleteResult> DeleteCascadingAsync <T>( IEnumerable <string> IDs, IClientSessionHandle session = null, CancellationToken cancellation = default) where T : IEntity { // note: cancellation should not be enabled outside of transactions because multiple collections are involved // and premature cancellation could cause data inconsistencies. // i.e. don't pass the cancellation token to delete methods below that don't take a session. // also make consumers call ThrowIfCancellationNotSupported() before calling this method. var db = Database <T>(); var options = new ListCollectionNamesOptions { Filter = "{$and:[{name:/~/},{name:/" + CollectionName <T>() + "/}]}" }; var tasks = new List <Task>(); // note: db.listCollections() mongo command does not support transactions. // so don't add session support here. var collNamesCursor = await db.ListCollectionNamesAsync(options, cancellation).ConfigureAwait(false); foreach (var cName in await collNamesCursor.ToListAsync(cancellation).ConfigureAwait(false)) { tasks.Add( session == null ? db.GetCollection <JoinRecord>(cName).DeleteManyAsync(r => IDs.Contains(r.ChildID) || IDs.Contains(r.ParentID)) : db.GetCollection <JoinRecord>(cName).DeleteManyAsync(session, r => IDs.Contains(r.ChildID) || IDs.Contains(r.ParentID), null, cancellation)); } var delResTask = session == null ? Collection <T>().DeleteManyAsync(x => IDs.Contains(x.ID)) : Collection <T>().DeleteManyAsync(session, x => IDs.Contains(x.ID), null, cancellation); tasks.Add(delResTask); if (typeof(T).BaseType == typeof(FileEntity)) { tasks.Add( session == null ? db.GetCollection <FileChunk>(CollectionName <FileChunk>()).DeleteManyAsync(x => IDs.Contains(x.FileID)) : db.GetCollection <FileChunk>(CollectionName <FileChunk>()).DeleteManyAsync(session, x => IDs.Contains(x.FileID), null, cancellation)); } await Task.WhenAll(tasks).ConfigureAwait(false); return(await delResTask.ConfigureAwait(false)); }
public bool CollectionExists(string collectionName) { try { var filter = new BsonDocument("name", collectionName); var options = new ListCollectionNamesOptions { Filter = filter }; return(MongoDatabase.ListCollectionNames(options).Any()); } catch (Exception) { throw new Exception("Could not check that MongoDB Collection: " + collectionName + " exists"); } }
public async void CreateCollAsync(string name) { var filter = new BsonDocument(name: "name", value: name); var options = new ListCollectionNamesOptions { Filter = filter }; var col = await MongoDatabase.ListCollectionNamesAsync(options); var any = await col.AnyAsync(); if (!any) { await MongoDatabase.CreateCollectionAsync(name : name); _logger.LogInformation($"--- Create collection with name \"{name}\""); } }
public static async Task CreateCollectionIfNotExists( this IMongoDatabase database, string name, CreateCollectionOptions?options = null, CancellationToken cancellationToken = default) { var filter = new ListCollectionNamesOptions { Filter = new BsonDocument("name", name) }; bool dbExists = await(await database.ListCollectionNamesAsync(filter, cancellationToken)) .AnyAsync(cancellationToken: cancellationToken); if (!dbExists) { await database.CreateCollectionAsync(name, options, cancellationToken); } }
public BlogsService(IDatabaseSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.Database); var filter = new BsonDocument("name", "BlogsCollection"); var options = new ListCollectionNamesOptions { Filter = filter }; bool collectionExist = database.ListCollectionNames(options).Any(); if (!collectionExist) { database.CreateCollection("BlogsCollection"); } _blogs = database.GetCollection <BlogCollection>("BlogsCollection"); }
private Lazy <IMongoCollection <TEntity> > CreateCollection() { return(new Lazy <IMongoCollection <TEntity> >(() => { var collectionFilter = new ListCollectionNamesOptions { Filter = Builders <BsonDocument> .Filter.Eq("name", CollectionName()) }; if (!mongoDatabase.ListCollectionNames(collectionFilter).Any()) { mongoDatabase.CreateCollection(CollectionName()); } var databaseCollection = mongoDatabase.GetCollection <TEntity>( CollectionName(), CollectionSettings() ?? new MongoCollectionSettings()); if (this.createShardKey) { try { Database.RunCommand <BsonDocument>(new BsonDocument { ["key"] = new BsonDocument { ["_id"] = "hashed" }, ["shardCollection"] = $"{mongoDatabase.DatabaseNamespace.DatabaseName}.{CollectionName()}" }); } catch (MongoException) { // Shared key probably created already. } } SetupCollection(databaseCollection); return databaseCollection; })); }
public Startup(IConfiguration configuration) { Configuration = configuration; // task to check if DB collection exists, if not create create and populate with CSV data try { var collectionName = configuration["CapstoneDatabaseSettings:Collections:0"]; var client = new MongoClient(configuration["CapstoneDatabaseSettings:ConnectionString"]); var db = client.GetDatabase(configuration["CapstoneDatabaseSettings:DatabaseName"]); var filter = new BsonDocument("name", collectionName); var options = new ListCollectionNamesOptions { Filter = filter }; // collection DNE if (!db.ListCollectionNames(options).Any()) { db.CreateCollection(collectionName); } var airportsCollection = db.GetCollection <Site>(collectionName); // no documents in collection or CLI flag was passed if (airportsCollection.AsQueryable().Count() < 1 || configuration["mongodb:force"] == "true") { System.Console.WriteLine("===Inserting data from \"./data/airports.json\" into MongoDB collection==="); // TODO: possibly make this task async string jsonTxt = File.ReadAllText("./data/airports.json", Encoding.UTF8); var records = JsonConvert.DeserializeObject <List <Site> >(jsonTxt); airportsCollection.InsertMany(records); } } catch (Exception e) { System.Console.WriteLine(e); System.Environment.Exit(-1); } }
protected virtual void CreateCollectionIfNotExists(string collectionName) { var stopwatch = Logger.StartStopwatch(); Logger.LogInformation("Start CreateCollectionIfNotExists with collection name {collectionName}", collectionName); var filter = new BsonDocument("name", collectionName); var options = new ListCollectionNamesOptions { Filter = filter }; if (!Database.ListCollectionNames(options).Any()) { Database.CreateCollection(collectionName); } stopwatch?.Stop(); Logger.LogInformation("End CreateCollectionIfNotExists, elapsed time: {elapsedTime}", Logger.GetElapsedTime(stopwatch)); stopwatch = null; }
private static async Task <DeleteResult> DeleteCascadingAsync <T>(IEnumerable <string> IDs, IClientSessionHandle session = null) where T : IEntity { // note: cancellation should not be enabled because multiple collections are involved // and premature cancellation could cause data inconsistencies. var db = Database <T>(); var options = new ListCollectionNamesOptions { Filter = "{$and:[{name:/~/},{name:/" + CollectionName <T>() + "/}]}" }; var tasks = new HashSet <Task>(); foreach (var cName in await db.ListCollectionNames(options).ToListAsync().ConfigureAwait(false)) { tasks.Add( session == null ? db.GetCollection <JoinRecord>(cName).DeleteManyAsync(r => IDs.Contains(r.ChildID) || IDs.Contains(r.ParentID)) : db.GetCollection <JoinRecord>(cName).DeleteManyAsync(session, r => IDs.Contains(r.ChildID) || IDs.Contains(r.ParentID), null)); } var delResTask = session == null ? Collection <T>().DeleteManyAsync(x => IDs.Contains(x.ID)) : Collection <T>().DeleteManyAsync(session, x => IDs.Contains(x.ID), null); tasks.Add(delResTask); if (typeof(T).BaseType == typeof(FileEntity)) { tasks.Add( session == null ? db.GetCollection <FileChunk>(CollectionName <FileChunk>()).DeleteManyAsync(x => IDs.Contains(x.FileID)) : db.GetCollection <FileChunk>(CollectionName <FileChunk>()).DeleteManyAsync(session, x => IDs.Contains(x.FileID), null)); } await Task.WhenAll(tasks).ConfigureAwait(false); return(await delResTask.ConfigureAwait(false)); }
public static async void CreateCollection(string name) { var filter = new BsonDocument("name", name); var options = new ListCollectionNamesOptions { Filter = filter }; if ((await database.ListCollectionNamesAsync(options)).Any() == false) { await database.CreateCollectionAsync(name); var collection = database.GetCollection <Record>(name); var indexOptions = new CreateIndexOptions() { Unique = true }; var collectionBuidler = Builders <Record> .IndexKeys; var indexModel = new CreateIndexModel <Record>(collectionBuidler.Ascending(x => x.key), indexOptions); await collection.Indexes.CreateOneAsync(indexModel); } }
private async Task InitializeCollection(CancellationToken cancellationToken) { var options = new ListCollectionNamesOptions(); options.Filter = Builders <BsonDocument> .Filter .Where(e => e["name"] == _collection); var collectionNamesCursor = await _database.ListCollectionNamesAsync(options, cancellationToken); var collectionName = await collectionNamesCursor.FirstOrDefaultAsync(cancellationToken); if (collectionName == null) { _logger?.LogDebug($"Creating collection `{_collection}`..."); await _database.CreateCollectionAsync(_collection, cancellationToken : cancellationToken); _logger?.LogDebug($"Collection `{_collection}` created successfully"); } else { _logger?.LogTrace($"Collection `{_collection}` already exists"); } }
protected virtual async Task CreateCollectionIfNotExistsAsync(string collectionName, CancellationToken cancellationToken = default) { var stopwatch = Logger.StartStopwatch(); Logger.LogInformation("Start CreateCollectionIfNotExistsAsync with collection name {collectionName}", collectionName); var filter = new BsonDocument("name", collectionName); var options = new ListCollectionNamesOptions { Filter = filter }; var result = await Database.ListCollectionNamesAsync(options, cancellationToken); if (!await result.AnyAsync(cancellationToken: cancellationToken)) { await Database.CreateCollectionAsync(collectionName, cancellationToken : cancellationToken); } stopwatch?.Stop(); Logger.LogInformation("End CreateCollectionIfNotExistsAsync, elapsed time: {elapsedTime}", Logger.GetElapsedTime(stopwatch)); stopwatch = null; }
public Task <IAsyncCursor <string> > ListCollectionNamesAsync(IClientSessionHandle session, ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default) => null;
public Task <IAsyncCursor <string> > ListCollectionNamesAsync(ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default) => null;
public static bool CheckForKeyDBAndSeed() { _mongoClient = new MongoClient("mongodb+srv://Steph:[email protected]/"); _mongoDatabase = _mongoClient.GetDatabase("KittenKeyDb"); var collection = _mongoDatabase.GetCollection <UniqueKeyDto>("KittenKeyDb"); var count = collection.CountDocumentsAsync(new BsonDocument()).Result; //exit if database is already present and populated if (count == _amount + 1) { return(true); } else { //to create the mongodb database and collection you must insert a record. var testKey = new UniqueKeyDto() { InUse = true, UniqueKey = "testKey" }; var testRecord = collection.Find(u => u.UniqueKey == testKey.UniqueKey).ToList(); //this will create the collection if (testRecord.Count == 0) { collection.InsertOne(testKey); } var filter = new BsonDocument("name", "KittenKeyDb"); var options = new ListCollectionNamesOptions { Filter = filter }; var collectionExists = _mongoDatabase.ListCollectionNames(options).Any(); //exit if the program has failed if (!collectionExists) { return(false); } else { _chars = _uniqueKeyCharSet.ToCharArray(); _listUniqueStrings = new List <string>(); var createPasswordsForDatabase = CreatePasswordsForKeyDb(); //if the number of passwords is not what we have set it to exit if (!(_listUniqueStrings.Count == _amount)) { return(false); } else { var passwords = GetUniqueKeyDtoList(); try { collection.InsertMany(passwords); } catch (Exception ex) { ex.ToString(); } } return(false); } } }
public Task <IAsyncCursor <string> > ListCollectionNamesAsync(IClientSessionHandle session, ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(Task.FromResult(ListCollectionNames(session, options, cancellationToken))); }
public Task <IAsyncCursor <string> > ListCollectionNamesAsync(ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(Task.FromResult(ListCollectionNames(options, cancellationToken))); }
public IAsyncCursor <string> ListCollectionNames(IClientSessionHandle session, ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(ListCollectionNames(options, cancellationToken)); }
public IAsyncCursor <string> ListCollectionNames(ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(new FakeAsyncCursor <string>(collections.Keys.ToArray())); }
public Task <IAsyncCursor <string> > ListCollectionNamesAsync(ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default) => _database.ListCollectionNamesAsync(_getSession(), options, cancellationToken);