MongoException: Index with name: code already exists with different options

faizi picture faizi · May 14, 2015 · Viewed 24.3k times · Source

I have a mongodb collection term with following structure

{
    "_id" : "00002c34-a4ca-42ee-b242-e9bab8e3a01f",
    "terminologyClass" : "USER",
    "code" : "X67",
    "terminology" : "some term related notes",
    "notes" : "some notes"
}

and a java class representing the term collection as Term.java

@Document
public class Term{  

    @Id
    protected String termId;

    @Indexed
    protected String terminologyClass;

    @Indexed(unique=true)
    protected String code;

    @Indexed
    protected String terminology;

    protected String notes;

    //getters & setters
}

I have many documents in term collection. Now I am added a new field to Term.java as

@Indexed
protected String status;

After adding field status to Term.java, while inserting a new term to term collection I am getting an the exceptoin :

com.mongodb.MongoException: Index with name: code already exists with different options

I am using MongoDB version : 2.6.5 and spring-data-mongodb version : 1.3.2

Answer

Ori Dar picture Ori Dar · May 14, 2015

You already have an index on that collection with the same name, but with a different definition. My guess is that your current code index is non-unique

try: db.Term.getIndexes()

If this is indeed the case (you have a non-unique index over code field), issue: db.Term.dropIndex("code_1") (replace with the code field index name).

Next time you boot your application, it's supposed to work alright.

Alternatively, remove the unique attribute from the @Indexed annotation (if you don't except it to be unique).