If you encounter the “index name must be a string” error when dropping multiple indexes in MongoDB, it’s probably because you’re passing the specifications document instead of the name.
When you use the dropIndexes()
method or the dropIndexes
command to drop multiple indexes, you need to pass the index names (not the specifications documents) in an array.
Example Indexes
Suppose we have the following indexes:
db.posts.getIndexes()
Result:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "title" : 1 }, "name" : "title_1" }, { "v" : 2, "key" : { "_fts" : "text", "_ftsx" : 1 }, "name" : "body_text", "weights" : { "body" : 1 }, "default_language" : "english", "language_override" : "language", "textIndexVersion" : 3 } ]
Problem Code
Here’s an example of code that causes this error:
db.posts.dropIndexes( [
{ "_fts" : "text", "_ftsx" : 1 },
{ "title" : 1 }
] )
Result:
uncaught exception: Error: error dropping indexes : { "ok" : 0, "errmsg" : "dropIndexes krankykranes.posts (f9083c2c-8291-49d1-95f7-40711186db98) failed to drop multiple indexes [ { _fts: \"text\", _ftsx: 1.0 }, { title: 1.0 } ]: index name must be a string", "code" : 14, "codeName" : "TypeMismatch" } : _getErrorWithCode@src/mongo/shell/utils.js:25:13 DBCollection.prototype.dropIndexes@src/mongo/shell/collection.js:692:11 @(shell):1:1
In this example, I’m trying to delete two indexes by passing their specification documents, but I get an error. I need to pass the index names instead.
Solution
To fix this problem, I simply need to pass the index names instead of their specification document:
db.posts.dropIndexes( [
"body_text",
"title_1"
] )
Result:
{ "nIndexesWas" : 3, "ok" : 1 }
That tells us that the indexes were dropped successfully.
Check the Results
We can run getIndexes()
again to verify that the indexes not longer exist.
db.posts.getIndexes()
Result:
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" } ]
Both indexes have been dropped as expected.