MongoDB Create index using C# .NET driver

Create MongoDB unique index using C driverMongoDB Create index using C NET driver

Today in this article, we shall see how to perform the MongoDB Create index using C# .NET driver.

As we understood in our previous article, the importance of indexes. Indexes can be created using CLI like mongo shell or UI interfaces like a compass or robomongo UI client or using code like node.js or C# mongo driver.

Today in this article, we will cover below aspects,

If you want to understand how to use MongoDB Compass UI to create indexes, Please use below article

Getting started

Please create any .NET/.NET Core application.

Please add the MongoDB driver NuGet package using the Nuget Package manager,

PM> Install-Package MongoDB.Driver -Version 2.9.3

Note: Please use the latest driver available

Step I – Establish the connection to the Database using MongoDB driver,

var _mongoClient = new MongoClient("mongodb://your connection string");
var db = _mongoClient.GetDatabase("your database name");

If using ASP.NET Core, please use dependency injection for injecting the driver instance,

Step2 – Create index script

Command

 { createIndexes: '<collection-name>', indexes: [ { key: { <indexed-fields-name>: 1 }, name: 'indexed-fields-name-custom', unique: true } ] }

Example

var commandStr = "{ createIndexes: 'TheCodeBuzzLib', indexes: [ { key: { AuthorId: 1 }, name: 'author-id', unique: true } ] }";

Step3 – Execute the script

 var result = _mongoClient.GetDatabase("TheCodeBuzzLib").RunCommand<BsonDocument>(commandStr);

Additionally, if needed we can use parse commands to parse the script,

 var cmd = BsonDocument.Parse(commandStr );
_mongoClient.GetDatabase("TheCodeBuzzLib").RunCommand<BsonDocument>(cmd);

Finally, you shall see indexes got for “author-id ” created successfully,

Create MongoDB indexes net

Approach 2

We can create indexes using another approach discussed in the below article

References:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.