MongoDB unique index is not working

groovy, java, mongodb

Solution

Possibly you haven't created the index properly.

Do it from the DB shell by executing the following statement:

db.refs.ensureIndex({customerReference: 1}, {unique : true})

Here, when I try to insert the document with the duplicate `customerReference` I receive an error, saying:

E11000 duplicate key error index: test.refs.$customerReference_1 dup key: { : 3.0 }

And when I execute the `db.refs.getIndexes()` command, I get:

{
    "v" : 1,
    "key" : {
        "customerReference" : 1
     },
     "unique" : true,
     "ns" : "test.refs",
     "name" : "customerReference_1"
 }

which shows that the unique index is created properly, but differs slightly from yours.

Update: When you're ensuring the index in the collection, you're making only one `BasicDBObject`, which will result in:

"key" : { "customerReference" : 1, "unique" : true }

Here, the value of the `key` shouldn't contain the `unique` attribute.

The `unique` attribute should be placed within the `index` document, like in mine code:

"key" : {
     "customerReference" : 1
 },
 "unique" : true

To create the index properly, you will have to provide two `BasicDBObjects`:

- one for `{customerReference : 1}`

- one for `{unique : true}`

Problem

I'm using Mongodb from Java. I create a collection and an index like this: ``` collection = mongoClient.getDB(DB_NAME).getCollection(COLLECTION_NAME) collection.ensureIndex(new BasicDBObject(['customerReference': 1, 'unique': true])) ``` when I check in the mongo shell i see: ``` { "v" : 1, "key" : { "customerReference" : 1, "unique" : true }, "ns" : "diagnostics.diagnosticData", "name" : "customerReference_1_unique_" } ``` but i can still insert duplicates: ``` { "_id" : ObjectId("52f3ba8a7d841c01680e0bc5"), "customerReference" : 3, "data" : "original data", "created" : ISODate("2014-02-06T16:38:34.191Z") } { "_id" : ObjectId("52f3ba8a7d841c01680e0bc6"), "customerReference" : 3, "data" : "duplicate data", "created" : ISODate("2014-02-06T16:38:34.194Z") } ``` why?

Original source