How to check if collection exists in MongoDB using C# driver?

前端 未结 3 760
小鲜肉
小鲜肉 2021-01-01 10:43

Is there any way in C# to check if a collection with a specific name already exists in my MongoDB database?

相关标签:
3条回答
  • 2021-01-01 11:20

    You can do it like this:

    database.GetCollection("blah").Exists()

    0 讨论(0)
  • 2021-01-01 11:23

    @Ofir answer is correct. Here's a synchronous alternative built around the ListCollectionNames API:

    public bool CollectionExists(IMongoDatabase database, string collectionName)
    {
        var filter = new BsonDocument("name", collectionName);
        var options = new ListCollectionNamesOptions { Filter = filter };
    
        return database.ListCollectionNames(options).Any();
    }
    
    0 讨论(0)
  • 2021-01-01 11:37

    @im1dermike answer is no longer working for c# driver version 2.0+

    Here is an alternative:

        public async Task<bool> CollectionExistsAsync(string collectionName)
        {
            var filter = new BsonDocument("name", collectionName);
            //filter by collection name
            var collections = await GetDatabase().ListCollectionsAsync(new ListCollectionsOptions { Filter = filter });
            //check for existence
            return await collections.AnyAsync();
        }
    
    0 讨论(0)
提交回复
热议问题