Changing an index in MongoDB

We are using the @Indexed annotation in Morphia and when we changed to @Indexed(unique=true) we were first surprised when nothing happened. Our first thought was that this might be a problem in Morphia. However, on second thought automatically changing an existing index is probably not a good idea! Although I couldn’t find anything in the documentation, MongoDB will not change the index if it already exists.

Have a look at the following to see what happens:


> db.Person.save({"name" : "foo" })
> db.Person.ensureIndex({"name":1})
> db.Person.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "test.Person",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"name" : 1
},
"ns" : "test.Person",
"name" : "name_1"
}
]
> db.Person.save({"name" : "foo" })
> db.Person.find()
{ "_id" : ObjectId("4ee9ab58e57f00e1f3ca95c7"), "name" : "foo" }
{ "_id" : ObjectId("4ee9ab63e57f00e1f3ca95c9"), "name" : "foo" }
> db.Person.ensureIndex({"name":1},{"unique":true, "dropDups":true})
> db.Person.find()
{ "_id" : ObjectId("4ee9ab58e57f00e1f3ca95c7"), "name" : "foo" }
{ "_id" : ObjectId("4ee9ab63e57f00e1f3ca95c9"), "name" : "foo" }
> db.Person.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "test.Person",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"name" : 1
},
"ns" : "test.Person",
"name" : "name_1"
}
]

Leave a Reply

Close Menu