MongoDB Shell and Basic Commands

Introduction to the MongoDB Shell (mongo shell) and essential commands for interacting with the database.


MongoDB Shell and Basic Commands

Introduction to the MongoDB Shell (mongo shell)

The MongoDB Shell, also known as mongo, is an interactive JavaScript interface to MongoDB. It allows you to connect to MongoDB instances, execute queries, and perform administrative operations directly from the command line. It's a powerful tool for interacting with your database, whether you're exploring data, running complex queries, or managing your MongoDB server.

Think of it as a terminal-based client that speaks directly to your MongoDB server. You type in commands, and the shell sends those commands to the server, which then executes them and sends back the results, which the shell then displays to you.

Connecting to a MongoDB Instance

To connect to a MongoDB instance, open your terminal or command prompt and type:

mongo

This will attempt to connect to a MongoDB instance running on the default host (localhost) and port (27017).

To connect to a specific host and port, use the following syntax:

mongo --host <hostname> --port <port>

For example:

mongo --host 192.168.1.100 --port 27017

If your MongoDB instance requires authentication, you'll need to provide the username, password, and authentication database. This can be done using connection strings or by specifying the authentication options directly in the shell.

Essential MongoDB Shell Commands

Here's a breakdown of some of the most commonly used commands in the MongoDB shell:

Database Management

  • show dbs: Lists all existing databases on the MongoDB server.
    show dbs
  • use <database_name>: Switches to a specific database. If the database doesn't exist, it will be created when you first store data in it.
    use mydatabase
  • db: Displays the name of the currently selected database.
    db

Collection Management

  • show collections: Lists all collections in the current database.
    show collections
  • db.createCollection("<collection_name>"): Creates a new collection in the current database.
    db.createCollection("users")
  • db.<collection_name>.drop(): Deletes a collection from the current database.
    db.users.drop()

Data Manipulation (CRUD Operations)

  • db.<collection_name>.insertOne(<document>): Inserts a single document into the collection.
    db.users.insertOne({ name: "John Doe", age: 30 })
  • db.<collection_name>.insertMany([<document1>, <document2>, ...]): Inserts multiple documents into the collection.
    db.users.insertMany([
      { name: "Jane Smith", age: 25 },
      { name: "Peter Jones", age: 40 }
    ])
  • db.<collection_name>.find(): Retrieves all documents in the collection.
    db.users.find()
  • db.<collection_name>.find(<query>): Retrieves documents that match the specified query.
    db.users.find({ age: { $gt: 28 } })
  • db.<collection_name>.findOne(<query>): Retrieves a single document that matches the specified query.
    db.users.findOne({name: "John Doe"})
  • db.<collection_name>.updateOne(<query>, <update>): Updates a single document that matches the specified query.
    db.users.updateOne({ name: "John Doe" }, { $set: { age: 31 } })
  • db.<collection_name>.updateMany(<query>, <update>): Updates multiple documents that match the specified query.
    db.users.updateMany({ age: { $lt: 30 } }, { $inc: { age: 1 } })
  • db.<collection_name>.deleteOne(<query>): Deletes a single document that matches the specified query.
    db.users.deleteOne({ name: "John Doe" })
  • db.<collection_name>.deleteMany(<query>): Deletes multiple documents that match the specified query.
    db.users.deleteMany({ age: { $gt: 35 } })

Helpful Tips

  • Tab Completion: The mongo shell supports tab completion. Start typing a command or collection name and press the Tab key to see available options.
  • help: Use the help command to get more information about a specific command or object. For example, db.collection.help() will show you the available methods for a collection.
  • Pretty Printing: Use the .pretty() method to format the output of your queries for better readability. For example, db.users.find().pretty().

These are just the basics. The MongoDB shell provides many more features and commands for advanced database administration and data analysis. Refer to the official MongoDB documentation for a comprehensive overview.