Quick Tip: mongorc.js

Did you know there is a special file you can edit and add some real useful features (as well as fun) every time you login to the MongoDB command line? Well Iā€™m gonna show you that now!

To use this, create a file called .mongorc.js in your home folder and paste this into it.

Of course this assumes you have the Databases and Collections in the example … so make sure to change those to make sense for your case … if you don’t your shell will just crash.

// šŸŒ® LearnMongo .mongorc.js example fun!
// !NOTE! In the real world you'd want to check for any "errors" as an error will crash your shell.

// auto set the database
db = db.getSiblingDB("test")

// .aggregate brings back a cursor, so we turn that into an array
const rc_joke = db.jokes.aggregate([{ $sample: { size: 1 } }]).toArray()[0];

//switch database to "cooker"
db = db.getSiblingDB("cooker")

const rc_database = db.getName();
const rc_collection = db.recipes.getName();
const rc_stats = db.stats();
const rc_collection_stats = db.recipes.stats();

// get a random recipe document
const rc_recipe = db.recipes.aggregate([{ $sample: { size: 1 } }]).toArray()[0];

print("šŸŽ­  "+rc_joke.setup);
print("šŸ¤”  "+rc_joke.punchline);
print(`Database: ${rc_database} | ${rc_stats.collections} Collections`); 
print(`Collection: ${rc_collection} | ${rc_collection_stats.count} Documents | ${rc_collection_stats.nindexes} Indexes`);
print("šŸ„˜ "+rc_recipe.title+" has "+rc_recipe.likes_count+" likes!");

prompt = function() {
    return "šŸ„Ø > ";

Leave a comment

Your email address will not be published. Required fields are marked *