Search code examples
mongodbmongodb-.net-driver

MongoDB duplicate index does not throw error


I am new to MongoDB and trying to make MongoDB throw an error when I insert another document with the same index. According to this answer MongoDB should throw an error.

The steps I did are: 1.) Add an index to Name field. I verified that it is added:

> db.room.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.room"
        },
        {
                "v" : 1,
                "key" : {
                        "Name" : 1
                },
                "name" : "Name_1",
                "ns" : "test.room"
        }
]

2.) I tried to add document with the same name and was able to add it:

> db.room.find().pretty()
{
        "_id" : 1,
        "ModifiedDate" : ISODate("2017-02-12T10:59:35.394Z"),
        "CreatedDate" : ISODate("2017-02-12T10:59:35.394Z"),
        "Name" : "Sample"
}
{
        "_id" : 2,
        "ModifiedDate" : ISODate("2017-02-12T10:59:39.474Z"),
        "CreatedDate" : ISODate("2017-02-12T10:59:39.474Z"),
        "Name" : "Sample"
}

I am using C# MongoDB Driver 2.4.


Solution

  • You have to specify that the index you are creating is unique, otherwise MongoDB will not enforce it. You can do that with the C# driver using the CreateIndexOptions class.

    roomCollection.Indexes
        .CreateOne(
            Builders<Room>.IndexKeys.Ascending(r => r.Name),
            new CreateIndexOptions() { Unique = true });
    

    Note that index creation will fail if there are currently duplicate names in the collection.