MongoDB server JavaScript script usage method

  • 2020-05-15 02:29:33
  • OfStack

Use JavaScript statements

 
db.getSiblingDB(<dbname>)  
db.getCollectionNames()   
db.getCollection(<collname>)   
db.printCollectionStats()

Run the JavaScript script on mongo shell

Switch database:


use <dbname>

Run the following script:


var total = 0;
var dbaStatCollections = function(){};
 
dbaStatCollections = function(){
  collNames = db.getCollectionNames();
  for (var index = 0; index < collNames.length; index++) {
    var coll = db.getCollection(collNames[index]); 
    var stats = coll.stats();
    print('ns,count,size,totalIndexSize');
  print(stats.ns + ',' + stats.count + ',' + stats.size + ',' + stats.totalIndexSize);
  }
}
 
dbaStatCollections();

You can save the above script as dbaStatCollections.js,

Run under linux shell


mongo localhost:27017/<dbname> dbaStatCollections.js

Or run under mongo shell


load("dbaStatCollections.js")

The JavaScript function is stored on the server side


db.system.js.remove({"_id":"dbaStatCollections"});
 
db.system.js.save(   
{
  _id : "dbaStatCollections" ,
  value : function () {
    collNames = db.getCollectionNames();
    for (var index = 0; index < collNames.length; index++) {
      var coll = db.getCollection(collNames[index]);
      var stats = coll.stats();
      print('ns,count,size,totalIndexSize');
      print(stats.ns + ',' + stats.count + ',' + stats.size + ',' + stats.totalIndexSize);
    }
  }
}
);
 
db.loadServerScripts();
 
dbaStatCollections();

You can use this function in the current JavaScript context. After exiting the session, the function is not saved. Can be executed only on Primary.

Note: the above output is saved as CSV file to open.
This is from the SQL Server Deep Dives blog


Related articles: