- Getting Started
- Admin Quick Tour
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
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 ListDatabases
or ListDatabasesAsync
methods.
using (var cursor = client.ListDatabases())
{
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document.ToString()));
}
}
using (var cursor = await client.ListDatabasesAsync())
{
await cursor.ForEachAsync(document => Console.WriteLine(document.ToString()));
}
Drop a Database
You can drop a database using the DropDatabase
or DropDatabaseAsync
methods.
client.DropDatabase("foo");
await client.DropDatabaseAsync("foo");
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:
var options = new CreateCollectionOptions { Capped = true, MaxSize = 1024 * 1024 };
database.CreateCollection("cappedBar", options);
await database.CreateCollectionAsync("cappedBar", options);
Drop a Collection
You can drop a collection with the DropCollection
or DropCollectionAsync
methods:
database.DropCollection("cappedBar");
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:
collection.Indexes.CreateOne(new BsonDocument("i", 1));
// or
var keys = Builders<BsonDocument>.IndexKeys.Ascending("i");
collection.Indexes.CreateOne(keys);
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 List
or ListAsync
methods to list the indexes in a collection:
using (var cursor = collection.Indexes.List())
{
foreach (var document in cursor.ToEnumerable())
{
Console.WriteLine(document.ToString());
}
}
using (var cursor = await collection.Indexes.ListAsync())
{
await cursor.ForEachAsync(document => Console.WriteLine(document.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:
collection.Indexes.CreateOne(new BsonDocument("content", "text"));
// or
var keys = Builders<BsonDocument>.IndexKeys.Text("content");
collection.Indexes.CreateOne(keys);
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
collection.InsertMany(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 = collection.CountDocuments(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 = collection.CountDocuments(filter);
Console.WriteLine("Text search matches (english): {0}", matchCount);
// find the highest scoring match
var projection = Builders<BsonDocument>.Projection.MetaTextScore("score");
var doc = collection.Find(filter).Project(projection).First();
Console.WriteLine("Highest scoring document: {0}", doc);
// 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.CountDocumentsAsync(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.CountDocumentsAsync(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 RunCommand
or RunCommandAsync
methods. Here we call the buildInfo command:
var buildInfoCommand = new BsonDocument("buildinfo", 1);
var result = database.RunCommand<BsonDocument>(buildInfoCommand);
var result = await database.RunCommandAsync<BsonDocument>(buildInfoCommand);