What is the syntax for creating a new unique index on a field using the c# driver?

There was a CreateIndexOptions that had a Unique bool property on it, but the overloads of collection.Indexes.CreateOne() that use that are marked as obsolete/deprecating. Now it uses a CreateOneIndexOptions that does not have a property for Unique. Where do I set an index to be unique?

On a separate note, I’m finding this c# driver is hard to follow along with and match to the corresponding Mongodb documentation. It feels like there are conventions or style that are unique to mongodb (and not common to .net) that may be getting followed, but its not mentioned or explained anywhere. It would be a great timesaver if that were part of the “Getting Started”.

Hello @Andrew_Stanton, welcome to the MongoDB Community forum!

Here is the code to create a Unique index on a field using C# Driver:

var dbClient = new MongoClient("mongodb://");
var db = dbClient.GetDatabase("test");
var collection = db.GetCollection<Books>("books");

// Create the unique index on the field 'title'
var options = new CreateIndexOptions { Unique = true };
collection.Indexes.CreateOne("{ title : 1 }", options);

// List all the indexes on the collection
var ixList = collection.Indexes.List().ToList<BsonDocument>();
ixList.ForEach(ix => Console.WriteLine(ix));

Here is the MongoDB C# Tutorial link for the Administration; see the specific topic Indexes within the same page.

There is also a Getting Started -> Admin Quick Tour. Look for the topic Indexes on the same page.

Thanks @Prasad_Saya, thats the way I’m doing it, but I have to add #pragma to disable the obsolete error.

I cant find the correct non-obsolete unique index creation function in this c# driver. Any ideas?

        var options = new CreateIndexOptions
            Unique = isUnique,
            Name = $"{collectionName}_{fieldName}"
#pragma warning disable CS0618 // Type or member is obsolete
        var createdIndexName = collection.Indexes.CreateOne($"{{ {fieldName} : 1 }}", options);
#pragma warning restore CS0618 // Type or member is obsolete

Hello @Andrew_Stanton, try this one.

This is by running the Database Command for createIndexes. The following creates a unique index on the title field of the books collection.

var cmdStr = "{ createIndexes: 'books', indexes: [ { key: { title: 1 }, name: 'title-uniq-1', unique: true } ] }";
var cmd = BsonDocument.Parse(cmdStr);
var result = mongoClient.GetDatabase("test").RunCommand<BsonDocument>(cmd);

Hi @Prasad_Saya,

How would you suggest going about checking the index is not already created?. Or is mongo handling duplicated index creation itself?. Thank you!.

Hello @Alejandro_Nagy, welcome to the MongoDB Community forum!

From mongo shell, you can run the following command to see all the indexes on a collection, e.g.,:


If you try to create the same index again, the command is ignored - the duplicated index creation is not possible.

1 Like