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

前端 未结 3 759
小鲜肉
小鲜肉 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:37

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

    Here is an alternative:

        public async Task 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();
        }
    

提交回复
热议问题