示例#1
0
        public bool CollectionExists(string collectionName)
        {
            var filter  = new BsonDocument("name", collectionName);
            var options = new ListCollectionNamesOptions {
                Filter = filter
            };

            return(database.ListCollectionNames(options).Any());
        }
示例#2
0
        private bool CollectionExists()
        {
            var filter  = new BsonDocument("name", _collectionName);
            var options = new ListCollectionNamesOptions {
                Filter = filter
            };

            return(_database.ListCollectionNames(options).Any());
        }
示例#3
0
        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());
        }
示例#4
0
        private bool CheckIfCollectionExists(IMongoDatabase database, string collectionName)
        {
            var nameFilter = new BsonDocument("name", collectionName);
            var options    = new ListCollectionNamesOptions {
                Filter = nameFilter
            };

            return(database.ListCollectionNames(options).Any());
        }
示例#5
0
        private bool TableExists(string _TableName)
        {
            var filter  = new BsonDocument("name", _TableName);
            var options = new ListCollectionNamesOptions {
                Filter = filter
            };

            return(MongoDB.ListCollectionNames(options).Any());
        }
示例#6
0
        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));
        }
示例#7
0
        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);
            }
        }
示例#9
0
    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);
        }
    }
示例#10
0
        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));
        }
示例#11
0
        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));
        }
示例#12
0
        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");
            }
        }
示例#13
0
        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}\"");
            }
        }
示例#14
0
        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);
            }
        }
示例#15
0
        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");
        }
示例#16
0
        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;
            }));
        }
示例#17
0
        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);
            }
        }
示例#18
0
        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;
        }
示例#19
0
        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));
        }
示例#20
0
        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");
            }
        }
示例#22
0
        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;
        }
示例#23
0
 public Task <IAsyncCursor <string> > ListCollectionNamesAsync(IClientSessionHandle session, ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default) => null;
示例#24
0
 public Task <IAsyncCursor <string> > ListCollectionNamesAsync(ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default) => null;
示例#25
0
        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()));
 }
示例#30
0
 public Task <IAsyncCursor <string> > ListCollectionNamesAsync(ListCollectionNamesOptions options = null, CancellationToken cancellationToken = default)
 => _database.ListCollectionNamesAsync(_getSession(), options, cancellationToken);