Skip to content

Instantly share code, notes, and snippets.

@PureKrome
Last active November 13, 2022 05:02
Show Gist options
  • Save PureKrome/b1a3a8399444be7f4d66d0c09ea420b2 to your computer and use it in GitHub Desktop.
Save PureKrome/b1a3a8399444be7f4d66d0c09ea420b2 to your computer and use it in GitHub Desktop.
πŸš€ MongoDB CLI newbie cheat sheet 🀘🏻

MongoDB -CLI- Cheat Sheet

  • You do NOT need to have MongoDB "installed" on your machine.
  • Leverage docker images and persist your data via docker 'volumes'.

Start a docker instance.

Create a mongo docker instance (from an image) and start a new shell (this is not a MongoDB shell .. just a normal BASH shell)

  • NOTE: check the volumn settings for your OS. This is a windows example, which connects the files in the current directly, to a specific folder inside the docker image.
docker run --rm -it -v ${PWD}:/src/scripts --name mongo-cli --network docker_default mongo /bin/bash

⚠️ NOTE: check the name of the network your existing docker images are running under. This could be defined in your docker-compose yml file if you're using docker compose.

Run commands inside the docker image.

Now that we're interacting/inside this instance, run a mongo script command: (this runs the mongo command which then executes a script under the mongo cli)

mongo --host mongodb.data --port 27017 --username root --password example file-to-execute-with-mongo-commands.js

or against a real server using a 'URI' connection string:

mongo "<uri>" <files.js>

NOTE: yes, the <uri> needs to be inside 2x quotes " ". And then the .js files at the end need to end with .js.

Customize the Mongo SHELL prompt:

Run this when you are inside/interacting with your mongodb cli instance:

host = db.serverStatus().host;
prompt = function() { return "db:[" + db + " @ " + host + "] >> "; }

Connection string

ref: https://docs.mongodb.com/manual/reference/connection-string/

"mongo": {
    "connectionString": "mongodb://username:password@localhost:27017"
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment