mongo

Master MongoDB shell commands with this comprehensive cheat sheet. Learn to connect, query, and manage your MongoDB databases effectively.

MongoDB Shell Commands

This page provides a comprehensive cheat sheet for the mongo shell client, essential for interacting with MongoDB databases. Learn how to connect to local and remote instances, specify databases, and execute scripts.

Connecting to MongoDB Instances

The mongo command is used to launch the interactive shell. Here are common connection scenarios:

# Connect to local host on default port 27017
mongo

# Connect to remote host on specified port
mongo --host 10.121.65.23 --port 23020

# Connect to a specific database on a host
mongo 10.121.65.58/mydb

# Connect with authentication and specified port/host
mongo -u username -p password --port 12345 --host localhost

# Connect to database on specified port and host
# and execute my-script.js after that
mongo localhost:27017/myDatabase my-script.js

Executing Scripts and Commands

You can run JavaScript files or evaluate single commands directly from the shell.

# Run the shell after executing my-script.js
mongo --shell my-script.js

# Evaluate a JavaScript expression on the database:
mongo --eval 'JSON.stringify(db.foo.findOne())' database

Additional Resources

For more information and advanced usage, refer to the official MongoDB documentation and related resources.

See also:

  • MongoDB cheat sheets at /mongo/
  • List of pages: /mongo/:list
  • Search in pages: /mongo/~keyword