How do you list indexes in MongoDb?
ArchanaK
Last updated on
Your thoughts?
Share your thoughts
there are few ways to list indexes...
the correct way is to do something like
db.people.getIndexes()
This returns something like this...
[ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_" }, { "v" : 2, "key" : { "name" : 1.0 }, "name" : "name_1" } ]
Notice how an array is returned with each index listed as an object.
For more info, check out List Indexes | MongoDB
So the official docs claim that you can get indexes for all collections like this...
db.getCollectionNames().forEach(function(collection) { indexes = db[collection].getIndexes(); print("Indexes for " + collection + ":"); printjson(indexes); });
Furthermore, they claim you can filter index types like this...
db.adminCommand("listDatabases").databases.forEach(function(d){ let mdb = db.getSiblingDB(d.name); mdb.getCollectionInfos({ type: "collection" }).forEach(function(c){ let currentCollection = mdb.getCollection(c.name); currentCollection.getIndexes().forEach(function(idx){ let idxValues = Object.values(Object.assign({}, idx.key)); if (idxValues.includes("hashed")) { print("Hashed index: " + idx.name + " on " + d.name + "." + c.name); printjson(idx); }; }); }); });
But REALLY these are just creative ways / scripts for using the only command for listing indexes..this is specific to a collection...
db.collection.getIndexes()
db.<collection>.getIndexes()
db.collection.getIndexes()
just check Robo3t or another DB tool and you can easily see indexes displayed via UI
BitCoinHypeTrain |
You can list all indexes in a collection like this...
You can list all indexes in a database like this...