Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 432
mclaassen Avatar asked Jul 29 '14 13:07

mclaassen


People also ask

How do you check if a collection already exists in MongoDB?

The collectionExists method can be used to check whether a collection is present or not: MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient. getDB("baeldung"); String testCollectionName = "student"; System.

How do I find a particular collection in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.

How do I show all collection data in MongoDB?

To get stats about MongoDB server, type the command db. stats() in MongoDB client. This will show the database name, number of collection and documents in the database.

Does MongoDB Create collection if not exists?

If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.


1 Answers

@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();     } 
like image 163
Ofir Avatar answered Sep 24 '22 00:09

Ofir