Basic Mongo Shell Commands Step by step Implementation and Top 10 Questions and Answers
 Last Update:6/1/2025 12:00:00 AM     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    14 mins read      Difficulty-Level: beginner

Basic MongoDB Shell Commands

The MongoDB shell, commonly referred to as mongo, is a powerful tool that provides a command-line interface to interact directly with a MongoDB database. It enables database administrators, developers, and analysts to perform various operations ranging from creating databases, collections, documents to running complex queries and administrative tasks without needing to write a full application. This guide covers essential MongoDB shell commands that every user should know to get started efficiently.

Connecting to the MongoDB Server

Firstly, you need to connect to your MongoDB server using the mongo shell. By default, MongoDB runs on localhost:27017. If you are connecting to the local server without authentication, simply open your terminal and type:

mongo

If MongoDB is hosted remotely or requires authentication, specify the host, port, username, password, and optionally the authentication database. For example:

mongo --host <hostname> --port <portnumber> -u <username> -p <password> --authenticationDatabase <authdb>

Navigating Databases

1. Show Databases To view all available databases, use the show dbs command.

show dbs

2. Switch Database Use use <databaseName> to switch to or create a new database. If the database doesn't exist, MongoDB will create it when you first store data.

use myDatabase

Working with Collections

1. Show Collections List all collections within the currently selected database using:

show collections

2. Drop Collection To delete a collection, execute the drop() method.

db.myCollection.drop()

CRUD Operations

CRUD (Create, Read, Update, Delete) operations are fundamental in any database interaction.

1. Create (Insert) Documents

  • Single Document: Use insertOne() to insert one document into a collection.

    db.myCollection.insertOne({ name: "John Doe", age: 30 })
    
  • Multiple Documents: Use insertMany() to add multiple documents at once.

    db.myCollection.insertMany([
        { name: "Jane Doe", age: 25 },
        { name: "Alice John", age: 40 }
    ])
    

2. Read (Find) Documents

  • Find All Documents

    db.myCollection.find()
    
  • Find Specific Documents

    Use criteria inside find() to filter results.

    db.myCollection.find({ age: 30 })
    
  • Pretty Print

    To format the output for better readability, chain .pretty() with find().

    db.myCollection.find().pretty()
    

3. Update Documents

  • Single Document

    Use updateOne() to modify only the first document that matches the specified criteria.

    db.myCollection.updateOne(
        { name: "John Doe" },
        { $set: { age: 31 } }
    )
    
  • Multiple Documents

    Use updateMany() to update all matching documents.

    db.myCollection.updateMany(
        { age: {$gt: 30} },
        { $inc: { age: 1 } }
    )
    

4. Delete Documents

  • Single Document

    Use deleteOne() to remove the first document that fulfills the condition.

    db.myCollection.deleteOne({ name: "Alice John" })
    
  • Multiple Documents

    Use deleteMany() to delete all documents that match the query.

    db.myCollection.deleteMany({ age: 31 })
    

Administrative Tasks

1. Display Current Database

Check which database you are currently working in.

```shell
db
```

2. List All Users

To see all users in a specific database, switch to that database and use:

```shell
use admin
db.getUsers()
```

3. Repair Database

If the database becomes corrupted due to power failures or other issues, use the `repairDatabase()` method. The database must be down during repair.

```shell
db.repairDatabase()
```

4. Backup and Restore

Although not directly performed via the shell, MongoDB’s backup (`mongodump`) and restore (`mongorestore`) utilities can be invoked from the command line while referencing the shell connection.

```shell
mongodump --db myDatabase
mongorestore --db myDatabase dump/myDatabase
```

5. Exit the MongoDB Shell

Simply type `exit` to leave the MongoDB shell.

```shell
exit
```

Conclusion

Understanding and mastering these basic MongoDB shell commands form a crucial foundation for anyone interacting with MongoDB databases. These commands empower users to perform routine operations such as reading, writing, and managing data efficiently, making them invaluable for development, administration, and data analysis tasks. As you grow more proficient, explore MongoDB's extensive documentation for advanced features and optimizations to further enhance your skills.




Examples, Set Route and Run the Application Then Data Flow: Step-by-Step Guide for Beginners to Basic MongoDB Shell Commands

Introduction

MongoDB is a NoSQL database that is widely used for modern web applications due to its scalability and flexibility. Working with MongoDB involves understanding basic commands and operations that allow you to interact with your data efficiently. In this guide, we'll explore basic MongoDB shell commands through a series of practical examples and steps to help beginners understand how to set up, manipulate, and retrieve data using MongoDB.

Prerequisites

Before diving into MongoDB commands:

  1. Installation: Ensure MongoDB Community Edition is installed on your machine.
  2. MongoDB Compass: Optional, but recommended as a graphical user interface for MongoDB.
  3. Node.js and npm: These will be used to create and run a simple Node.js application.

Step 1: Launching the MongoDB Shell

After installation, you can launch the MongoDB shell to interact with your MongoDB instance.

  1. Open Terminal/Command Prompt.

  2. Run mongo command:

    mongo
    

    This should connect you to the default MongoDB server running locally.

Step 2: Setting Up a New Database and Collection

Let's start by creating a new database named testdb and a collection named users.

  1. Create a new database:

    use testdb
    

    If testdb doesn't exist, it will be created.

  2. Create a new collection:

    db.createCollection('users')
    

    Alternatively, if you insert data, MongoDB creates the collection automatically.

Step 3: Inserting Data into the Collection

Now, let's add some sample documents to the users collection.

  1. Insert a single document:

    db.users.insertOne({ name: 'Alice', age: 30, email: 'alice@example.com' })
    
  2. Insert multiple documents:

    db.users.insertMany([
      { name: 'Bob', age: 25, email: 'bob@example.com' },
      { name: 'Charlie', age: 33, email: 'charlie@example.com' }
    ])
    

Step 4: Querying Data from the Collection

Next, we'll learn how to retrieve data stored in the users collection.

  1. Find all documents:

    db.users.find()
    
  2. Find documents matching a specific criteria:

    db.users.find({ age: 30 })
    
  3. Retrieve specific fields from documents:

    db.users.find({}, { name: 1, _id: 0 })
    
  4. Use the pretty() method for readable output:

    db.users.find().pretty()
    

Step 5: Updating Documents

Updating existing documents in MongoDB allows us to make changes without creating duplicates.

  1. Update a single document:

    db.users.updateOne(
      { name: 'Alice' },
      { $set: { age: 31 } }
    )
    
  2. Update multiple documents:

    db.users.updateMany(
      { age: { $gt: 28 } },
      { $inc: { age: 1 } }
    )
    

Step 6: Deleting Documents

Sometimes, it’s necessary to remove documents from your MongoDB collection.

  1. Delete a single document:

    db.users.deleteOne({ name: 'Bob' })
    
  2. Delete multiple documents:

    db.users.deleteMany({ age: { $lt: 33 } })
    

Step 7: Creating a Simple Node.js Application to Interact with MongoDB

Now, let's build a basic Node.js application to interact with our MongoDB database.

  1. Initialize a new Node.js project:

    mkdir my_mongo_app
    cd my_mongo_app
    npm init -y
    
  2. Install MongoDB Node.js driver:

    npm install mongodb
    
  3. Create an app.js file:

    const { MongoClient } = require('mongodb');
    const uri = "mongodb://localhost:27017";
    const client = new MongoClient(uri);
    
    async function runApp() {
     try {
       await client.connect();
       const database = client.db('testdb');
       const users = database.collection('users');
    
       // Insert one document
       const insertResult = await users.insertOne({
         name: 'David',
         age: 28,
         email: 'david@example.com'
       });
       console.log("Inserted User:", insertResult.insertedId);
    
       // Find all documents
       const cursor = users.find({});
       await cursor.forEach(doc => console.log(doc));
    
     } finally {
       await client.close();
     }
    

}

runApp().catch(console.dir);


4. **Run the application**:

```bash
node app.js

This script connects to your local MongoDB server, inserts a new user, and retrieves all users in the users collection.

Conclusion

This step-by-step guide covered basic MongoDB shell commands along with setting up a simple Node.js application. By following these instructions, you should now understand how to create databases and collections, insert, query, update, and delete data in MongoDB. Practice these commands regularly to become proficient in managing MongoDB data effectively.

Feel free to explore more advanced features and operations in MongoDB as you continue your journey with NoSQL databases. Happy coding!




Top 10 Questions and Answers About Basic MongoDB Shell Commands

1. What is the MongoDB shell?

Answer: The MongoDB shell, also known as mongo, is an interactive JavaScript-based interface to MongoDB that allows users to interact with their databases directly from the command line. It's a powerful tool for database administrators and developers alike to query, update, and manage MongoDB databases without writing a complete application.

2. How do I start the MongoDB shell?

Answer: To start the MongoDB shell, open your terminal or command prompt and simply type mongo. Make sure your MongoDB server is running before you attempt to connect. If the server is not running, start it by using the mongod command.

$ mongo
MongoDB shell version v4.4.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("5f1b2c3d-4e5f-6a7b-8c9d-e0f123456789") }
MongoDB server version: 4.4.6

3. How do I list all the databases in MongoDB?

Answer: Use the show dbs command to display a list of all available databases. Note that newly created databases will only appear in this list if they contain collections with at least one document.

> show dbs
admin  0.000GB
config 0.000GB
local  0.000GB

4. How can I switch between databases?

Answer: To switch to an existing database (or create a new one if it doesn't exist), use the use <database_name> command. After switching, the database context for subsequent operations is set to the selected database.

> use myDatabase
switched to db myDatabase

5. How do I list all collections in the current database?

Answer: To view all collections within the currently selected database, use the show collections (or show tables) command.

> show collections
collectionOne
collectionTwo

6. How do I insert a single document into a collection?

Answer: You can insert a document into a collection using the db.collection.insertOne() method. If the collection does not already exist, MongoDB creates it when you attempt to insert a document.

> db.collectionOne.insertOne({name: "John Doe", age: 28 })
{
    "acknowledged": true,
    "insertedId": ObjectId("5fa1b2c3d4e5f6a7b8c9d0e1")
}

7. How do I retrieve all documents from a collection?

Answer: To fetch all documents from a collection, use the find() method on the specific collection.

> db.collectionOne.find()
{ "_id" : ObjectId("5fa1b2c3d4e5f6a7b8c9d0e1"), "name" : "John Doe", "age" : 28 }
{ "_id" : ObjectId("5fb2c3d4e5f6a7b8c9d0e1f2"), "name" : "Jane Smith", "age" : 34 }

To make the output more readable, you can pretty-print it using the .pretty() method:

> db.collectionOne.find().pretty()
{
    "_id" : ObjectId("5fa1b2c3d4e5f6a7b8c9d0e1"),
    "name" : "John Doe",
    "age" : 28
}
{
    "_id" : ObjectId("5fb2c3d4e5f6a7b8c9d0e1f2"),
    "name" : "Jane Smith",
    "age" : 34
}

8. How do I find a document that matches a specific condition?

Answer: Use the find() method with a query object to search for documents that match specific criteria.

> db.collectionOne.find({ name : "John Doe" }).pretty()
{
    "_id" : ObjectId("5fa1b2c3d4e5f6a7b8c9d0e1"),
    "name" : "John Doe",
    "age" : 28
}

To find a single match, use the findOne() method:

> db.collectionOne.findOne({ name : "Jane Smith" })
{ "_id" : ObjectId("5fb2c3d4e5f6a7b8c9d0e1f2"), "name" : "Jane Smith", "age" : 34 }

9. How do I update a document in MongoDB?

Answer: To modify an existing document, use the updateOne() or updateMany() methods. For example, to update the age of "John Doe":

> db.collectionOne.updateOne(
    { name: "John Doe" },
    { $set: { age: 29 } }
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

To verify the update, retrieve the document again:

> db.collectionOne.findOne({ name: "John Doe" }).pretty()
{
    "_id" : ObjectId("5fa1b2c3d4e5f6a7b8c9d0e1"),
    "name" : "John Doe",
    "age" : 29
}

10. How do I delete documents from a collection?

Answer: To remove documents, use the deleteOne() or deleteMany() methods. To delete a single document where name is "Jane Smith":

> db.collectionOne.deleteOne({ name: "Jane Smith" })
{ "acknowledged" : true, "deletedCount" : 1 }

After deleting, try retrieving the document to confirm:

> db.collectionOne.findOne({ name: "Jane Smith" })
null

These commands provide a foundation for working with MongoDB through its shell interface, enabling you to manage and manipulate data efficiently. As you grow more familiar with MongoDB, you can explore advanced commands and features to enhance your data management capabilities.