MongoDB C# Create Index case insensitive

problem

By default indexes you create in MongoDB are case sensitive.

How to create a case insensitive index using the C# client?

solution

You have to specify the collation when creating the index, and set a collation strength for it.

Here is some sample code:

var mongoConnectionString = "your-mongo-connection-string";

var mongoClient = new MongoClient(mongoConnectionString);
var database = mongoClient.GetDatabase("Inventory");
var productCollection = database.GetCollection<Product>("Products");

var createIndexModel =
    new CreateIndexModel<Product>(Builders<Product>.IndexKeys.Ascending(i => i.ProductReference),
        new CreateIndexOptions
        {
            Collation = new Collation("en", false, CollationCaseFirst.Off, CollationStrength.Secondary)
        });
productCollection.Indexes.CreateOne(createIndexModel);
Gravatar
Author
Dan Dumitru
Last Edit
Aug 31, 2022 at 09:05

1 Comment


A warning so you don't lose an hour like I did: Atlas Serverless instances do not support collation, it simply does not create the index if you try to use them.

Gravatar
Frodo
Jan 25, 2023 at 14:03

Your Comment

Feel free to add your improvement suggestions or alternative solutions.
preview
Optional, never shown, displays gravatar.

Formatting Tips

This editor uses Markdown to easily add code in your posts.

Triple backticks for full line(s) of code (or indent 4 spaces)

```
let foo = 'bar';
```

[link text](http://a.com)

*italic* **bold**

More Tips