Is there any way in C# to check if a collection with a specific name already exists in my MongoDB database?
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.
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.
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.
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.
@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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With