Create MongoDB indexes in C#.NET – II

Create MongoDB unique index using C driver

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

This article lists a new approach to creating the index. If you’re interested to know about the first approach which we discussed please visit this article.

Today in this article, we will cover below aspects,

In our last article, we used another approach of command script and executed the script using the RunCommand() method to create the indexes.

Also, we understood in our previous article, the importance of indexes.

Indexes can be created using CLI like a mongo shell or UI interfaces like a compass or robomongo UI client or using code like node.js or C# mongo driver.

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

Getting started

Please create any C# .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

Connect Database using MongoDB driver

Step I – Establish the connection to the Database using the 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 using Index builder

Define the index name which will be one of the mongo fields in the database schema.

Please follow best practices on indexing before creating an index or compound index.

              var indexKeysDefine= Builders<Library>.IndexKeys.Ascending(indexKey => indexKey.Name);
          

await collection.Indexes.CreateOneAsync(new CreateIndexModel(indexKeysDefine)); 

Create MongoDB indexes in CNET

Below is Libary Mongo schema/domain object defined representing the document.

public class Library
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public ObjectId Id { get; set; }

        public string userId { get; set; }
        public string Name { get; set; }
        public Books[] BooksCategories { get; set; }
    }

Finally, you shall see indexes go created successfully,

CreateIndexModel

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.



Leave a Reply

Your email address will not be published. Required fields are marked *