FinalFive
FinalFive

Reputation: 1485

MongoDB unique index is not working

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?

Upvotes: 5

Views: 5264

Answers (2)

Hasan
Hasan

Reputation: 377

I'm using mongoose for JavaScript but I think that the solution that I found well also work for other languages... When you connect your database with the application add this option: "audoIndex: true" for example in JS we'll do something like this:

const options = {
// your options go here
...
// this code is the solution
audoIndex: true
}
mongoose.connect(DB_URI, options);

I also dropped the collection that I have problem with and recreated it to make sure that it will work. I found this solution at: https://dev.to/emmysteven/solved-mongoose-unique-index-not-working-45d5 I also tried solutions like "restart MongoDB" but didn't work for me.

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62854

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}

Upvotes: 3

Related Questions