I am fighting to create a unique field EmailAddress. I\'ve already seen in forums that I have to create an index, but it didn\'t work out for me so far. Does an
EnsureIndex() is deprecated/obsolete per the C# mongo drivers version 2.0 spec: http://api.mongodb.org/csharp/current/html/M_MongoDB_Driver_MongoCollection_EnsureIndex_2.htm
heres how to do it async and via 2.0 code:
var mongoClient = new MongoClient("connection");
var db = mongoClient.GetDatabase("database");
var options = new CreateIndexOptions() { Unique = true };
var field = new StringFieldDefinition("EmailAddress");
var indexDefinition = new IndexKeysDefinitionBuilder().Ascending(field);
await db.GetCollection("users").Indexes.CreateOneAsync(indexDefinition, options);
In case of a non-string index:
var options = new CreateIndexOptions() { Unique = true };
IndexKeysDefinition keyCode = "{ Code: 1 }";
var codeIndexModel = new CreateIndexModel(keyCode, options);