How to run script in MongoDB both in onpremise and atlas

Hi All,

I am new to MongoDB. I want to execute some scripts in MongoDB.
Please advise how I can run as script.

I can connect to Atlas cluster using shell. But not sure how to run scripts from shell.

sample script to run:

var totalSize = 0;
var totalReusableSize = 0;

// Print table header
print(“-------------------------------------------------------------------”);
print(“| Namespace | Count | Storage Size (bytes) | Reusable Size (bytes) |”);
print(“-------------------------------------------------------------------”);

var stat = db.getSiblingDB(‘local’).getCollection(‘mytest’).stats();
var namespace = stat.ns;
var count = stat.count;
var storageSize = stat.storageSize;
var reusableSize = stat.wiredTiger[“block-manager”][“file bytes available for reuse”];
totalSize += storageSize;
totalReusableSize += reusableSize;

// Format and print row data
print(“| " + namespace.padEnd(14) + " | " + count.toString().padEnd(10) + " | " + storageSize.toString().padEnd(21) + " | " + reusableSize.toString().padEnd(21) + " |”);

// Print table footer
print(“-------------------------------------------------------------------”);

print(“\nTotal Storage Size: " + totalSize + " bytes”);
print(“Total Reusable Size: " + totalReusableSize + " bytes”);

Please advise with command as I am not familiar on this.

Use the MongoDB Shell mongosh

  • You can use mongosh as a command-line tool to connect to your cluster in order to:
    • issue interactive queries
    • load and run scripts
  • You can run mongosh from within Compass, the MongoDB Gui