Codeinator
Codeinator

Reputation: 719

How to drop non-unique index only?

I have the following index in my databases (yes, I have a couple of them).

{
    "v" : 1,
    "key" : {
        "someUniqueField" : 1
    },
    "name" : "someUniqueField_1",
    "ns" : "MyDB.Collection"
}

But actually, I wanted to have a unique index. I changed the create index statement for newer databases. But now I have different versions of this index in different databases.

Now I want to delete just thus indexes with unique: false (or with no unique field, displayed in the getIndexes() output).

This commands would drop the index independent of the unique flag.

db.collection.dropIndex("someUniqueField_1"); // or
db.collection.dropIndex({"someUniqueField": 1});

Is there something like:

db.collection.dropIndex({"someUniqueField": 1}, {unique: false});

I know I could drop all these indices and create a new one, or I could check it manually if the wrong index exists.

But it would be also nice for learning purposes if this is possible.

Upvotes: 1

Views: 421

Answers (1)

Vao Tsun
Vao Tsun

Reputation: 51529

this should give you the script?

db.a.getIndexes().forEach(function(k) { 
  if (k.key.unique != 1) {
    print("db.a.dropIndex(\"k.name\");");
  }
});

Upvotes: 1

Related Questions