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 adminstrative functions. In the first part, we looked at how to perform basic CRUD (create, read, update, delete) operations.

Note
See the installation guide for instructions on how to install the MongoDB Driver.

Setup

To get started we’ll quickly connect and create client, database, and collection variables for use in the examples below:

var client = new MongoClient();
var database = client.GetDatabase("foo");
var collection = client.GetCollection<BsonDocument>("bar");

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.

List the Databases

You can list all the databases using the ListDatabasesAsync method.

using (var cursor = await client.ListDatabasesAsync())
{
    await cursor.ForEachAsync(d => Console.WriteLine(d.ToString()));
}

Drop a Database

You can drop a database using the DropDatabaseAsync method.

await client.DropDatabaseAsync("foo");

Create a Collection

A collections in MongoDB is created automatically simply by inserting a document into it. Using the CreateCollectionAsync method, 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:

var options = new CreateCollectionOptions { Capped = true, MaxSize = 1024 * 1024 };

await database.CreateCollectionAsync("cappedBar", options);

Drop a Collection

You can drop a collection with the DropCollectionAsync method:

await database.DropCollectionAsync("cappedBar");

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:

await collection.Indexes.CreateOneAsync(new BsonDocument("i", 1));

// or

var keys = Builders<BsonDocument>.IndexKeys.Ascending("i");
await collection.Indexes.CreateOneAsync(keys);

More information about the IndexKeys definition builder is in the reference section.

List the Indexes in a Collection

Use the ListAsync method to list the indexes in a collection:

using (var cursor = await collection.Indexes.ListAsync())
{
    await cursor.ForEachAsync(i => Console.WriteLine(i.ToString()));    
}

The example should print the following indexes:

{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "mydb.test" }
{ "v" : 1, "key" : { "i" : 1 }, "name" : "i_1", "ns" : "mydb.test" }

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:

await collection.Indexes.CreateOneAsync(new BsonDocument("content", "text"));

// or

var keys = Builders<BsonDocument>.IndexKeys.Text("content");
await collection.Indexes.CreateOneAsync(keys);

As of MongoDB 2.6, text indexes are now integrated into the main query language and enabled by default:

// insert some documents
await collection.InsertManyAsync(new []
{
    new BsonDocument("_id", 0).Add("content", "textual content"),
    new BsonDocument("_id", 1).Add("content", "additional content"),
    new BsonDocument("_id", 2).Add("content", "irrelevant content"),
});

// find them using the text index
var filter = Builders<BsonDocument>.Filter.Text("textual content -irrelevant");
var matchCount = await collection.CountAsync(filter);
Console.WriteLine("Text search matches: {0}", matchCount);

// find them using the text index with the $language operator
var englishFilter = Builders<BsonDocument>.Filter.Text("textual content -irrelevant", "english");
var matchCount = await collection.CountAsync(filter);
Console.WriteLine("Text search matches (english): {0}", matchCount);

// find the highest scoring match
var projection = Builders<BsonDocument>.Projection.MetaTextScore("score");
var doc = await collection.Find(filter).Project(projection).FirstAsync();
Console.WriteLine("Highest scoring document: {0}", doc);

and it should print:

Text search matches: 2
Text search matches (english): 2
Highest scoring document: { "_id" : 1, "content" : "additional content", "score" : 0.75 }

For more information about text search, see the text index and the $text query operator documentation.

Running a Command

Not all commands have a specific helper, however you can run any command by using the RunCommandAsync method. Here we call the buildInfo command:

var buildInfoCommand = new BsonDocument("buildinfo", 1);
var result = await database.RunCommandAsync(buildInfoCommand);