title: C# MongoDB driver: unique index
body: <p>I have a model with _id, name and other fields. I want to create an index so it would be impossible to save documents with same names. I'm creating an index such way:</p>
  <pre><code>public static async Task EnsureIndexExists(this IMongoDatabase database, string collectionName, string indexName)
          {
              var collection = database.GetCollection&lt;BsonDocument&gt;(collectionName);
              var builder = Builders&lt;BsonDocument&gt;.IndexKeys;
              var field = new StringFieldDefinition&lt;BsonDocument&gt;(indexName.FromPascalToCamel());
              var indexModel = new CreateIndexModel&lt;BsonDocument&gt;(builder.Ascending(field));
              await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false);
          }
  
  // ...
  
  database.EnsureIndexExists(CharacterRepository.CollectionName, nameof(CharacterEntity.Name)).Wait();
  </code></pre>
  <p>The model:</p>
  <pre><code>public class CharacterEntity
      {
          [BsonId]
          [BsonRepresentation(BsonType.ObjectId)]
          public string Id { get; set; }
          public string Name { get; set; }
          //...
      }
  </code></pre>
  <p>But still documents with the same names can be saved into DB.</p>
  <p>The driver versions:</p>
  <pre><code>&lt;PackageReference Include=&quot;AspNetCore.Identity.MongoDbCore&quot; Version=&quot;2.1.1&quot; /&gt;
  &lt;PackageReference Include=&quot;MongoDB.Driver&quot; Version=&quot;2.11.1&quot; /&gt;
  </code></pre>
  <p>What I'm doing wrong?</p>