mongodb indexes

41 views
Skip to first unread message

Kushal Shreyas

unread,
Feb 13, 2020, 6:20:26 AM2/13/20
to mongodb-user
Is a there a way to check for indexes for all the dbs in the mongod server.
In case we have 50 collections within a single db then it will be difficult to check each collection and get indexex info.

So can anyone help me hw to know how many indexes are there in the mongo server for all dbs?

Regards
Manu

MH

unread,
Feb 13, 2020, 9:06:45 AM2/13/20
to mongodb-user
I've used this in the past to export all indexes

db.getCollectionNames().forEach(function(collection) {
indexes = db[collection].getIndexes();
indexes.forEach(function (c) {
opt = ''
ixkey = JSON.stringify(c.key, null, 1).replace(/(\r\n|\n|\r)/gm,"")
ns = c.ns.substr(c.ns.indexOf(".") + 1, c.ns.length)
for (var key in c) {
 if (key != 'key' && key != 'ns' && key != 'v') {
 if (opt != '') { opt+= ','}       
 if (c.hasOwnProperty(key)) {
   if (typeof(c[key]) == "string") {
        opt +=  (key + ': "' + c[key] + '"')
      } else  {
        opt+=  (key + ": " + c[key])
       }
     }
   }
  }
  if (opt != '') { opt = '{' + opt + '}'}
  print ('db.' + ns + '.ensureIndex(' + ixkey + ','+  opt + ')')
 })});
Reply all
Reply to author
Forward
0 new messages