MongoDB Driver Admin Quick Tour

This is the second part of the MongoDB driver quick tour. In this part, we’ll look at performing some administrative functions. In the first part, we looked at how to perform basic CRUD (create, read, update, delete) operations.

Note

Calling the GetDatabase method on client does not create a database. Likewise, calling the GetCollection<BsonDocument> method on database will not create a collection. Only when a database or collection are written to will they be created. Examples include the creation of an index or the insertion of a document into a previously non-existent collection.

Drop a Database

Create a Collection

A collection in MongoDB is created automatically simply by inserting a document into it. Using the CreateCollection or CreateCollectionAsync methods, you can also create a collection explicitly in order to to customize its configuration. For example, to create a capped collection sized to 1 megabyte:

Drop a Collection

Create an Index

MongoDB supports secondary indexes. To create an index, you just specify the field or combination of fields, and for each field specify the direction of the index for that field; 1 for ascending and -1 for descending. The following creates an ascending index on the i field:

Text Indexes

MongoDB also provides text indexes to support searching of string content. Text indexes can include any field whose value is a string or an array of string elements. To create a text index specify the string literal “text” in the index document: