0

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:

public static async Task EnsureIndexExists(this IMongoDatabase database, string collectionName, string indexName)
        {
            var collection = database.GetCollection<BsonDocument>(collectionName);
            var builder = Builders<BsonDocument>.IndexKeys;
            var field = new StringFieldDefinition<BsonDocument>(indexName.FromPascalToCamel());
            var indexModel = new CreateIndexModel<BsonDocument>(builder.Ascending(field));
            await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false);
        }

// ...

database.EnsureIndexExists(CharacterRepository.CollectionName, nameof(CharacterEntity.Name)).Wait();

The model:

public class CharacterEntity
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        public string Name { get; set; }
        //...
    }

But still documents with the same names can be saved into DB.

The driver versions:

<PackageReference Include="AspNetCore.Identity.MongoDbCore" Version="2.1.1" />
<PackageReference Include="MongoDB.Driver" Version="2.11.1" />

What I'm doing wrong?

1 Answer 1

2

I just had to add CreateIndexOptions:

public static async Task EnsureIndexExists(this IMongoDatabase database, string collectionName, string indexName)
        {
            var collection = database.GetCollection<BsonDocument>(collectionName);
            indexName = indexName.FromPascalToCamel();

            var index = new BsonDocument
            {
                {indexName, 1}
            };

            var indexModel = new CreateIndexModel<BsonDocument>(index, new CreateIndexOptions { Unique = true });
            await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false);
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.