Unable to get Index on field working. Documents with same field name are added

Using .Net MongDb.Driver version 3.2.

Call this code once:

 IMongoCollection<Contest> Contests = iMongoDatabase!.GetCollection<Contest>(collectionName);

 var indexModel = new CreateIndexModel<Contest>(Builders<Contest>.IndexKeys.Ascending(c => c.Name));

 Contests.Indexes.CreateOne(indexModel);

Then I call InsertOne twice, using the same Name value. I’d expect only one Document to get inserted but both are inserted with the same Name.

Github repo: GitHub - skippyV/MongoDbNetIndexTest: Testing Indexes on MongoDB with .Net driver

Hi @Skippy_VonDrake

To prevent duplicates being added to the collection a unique index needs to be created.

Create the index with the correct option and you’ll be :+1:

ref:
https://www.mongodb.com/docs/drivers/csharp/current/fundamentals/indexes/#unique-indexes

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.