May 11, 2026

MongoDB Shell (mongosh)

MongoDB Shell Overview

mongosh (MongoDB Shell) is an interactive JavaScript-based shell used to interact with MongoDB databases. It replaces the legacy mongo shell and provides a modern, developer-friendly experience with better usability and scripting capabilities. 

Whether you're debugging data issues, running quick queries, or executing scripts—mongosh is your most powerful direct interface to MongoDB.

When to Use mongosh vs MongoDB Compass

Both mongosh and MongoDB Compass are powerful tools for interacting with MongoDB, but they serve different purposes depending on the task.

MongoDB Compass — Best for Visualization & Exploration

MongoDB Compass is ideal when you want a visual interface to explore your database without writing commands manually.

Use Compass when you need to:

  • Browse collections visually
  • Inspect document structures
  • Quickly test simple queries
  • View indexes and schema information
  • Analyze aggregation pipelines visually
  • Work comfortably with smaller datasets

Compass is especially useful for beginners or during early-stage debugging where seeing the data structure helps more than scripting.

However, Compass has limitations when operations become more complex or repetitive.

mongosh — Best for Power Operations & Automation

mongosh gives developers direct control over MongoDB using JavaScript-based commands and scripts.

Use mongosh when you need to:

  • Perform bulk updates or deletions
  • Run loops and conditional logic
  • Execute migration or cleanup scripts
  • Handle duplicate data removal
  • Automate repetitive database tasks
  • Debug production-level data issues
  • Run advanced aggregation workflows
  • Execute commands faster than GUI interactions

Unlike Compass, mongosh allows scripting and automation, making it extremely valuable for backend developers and DevOps workflows.

For example:

  • Removing thousands of duplicate records
  • Updating fields across multiple collections
  • Writing one-time migration scripts
  • Performing production hotfixes

These tasks are significantly easier and more efficient in mongosh.

Which One Should You Choose?

In practice, developers often use both tools together:

  • Use Compass for exploration and visualization
  • Use mongosh for execution, automation, and production fixes

Think of Compass as the visual dashboard, while mongosh is the developer power tool for serious database operations.

Connecting to mongosh

Inside MongoDB Compass

  1. Open MongoDB Compass
  2. Connect to your database
  3. Click the >_ MONGOSH tab
  4. Start writing commands

Basic Commands

Switch Database

  use myDatabase

Show Collections

  show collections

Find Data

  db.users.find()

CRUD Operations

Insert

  db.users.insertOne({ name: "John", age: 30 })

Read

  db.users.find({ age: { $gt: 25 } })

Update

  db.users.updateOne(
  { name: "John" },
  { $set: { age: 31 } }
)

Delete

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

Running Aggregation Pipelines

Aggregation pipelines are used to process and transform data in MongoDB.

db.orders.aggregate([
  { $match: { status: "completed" } },
  {
    $group: {
      _id: "$customerId",
      total: { $sum: "$amount" }
    }
  }
])

Real-World Use Case: Removing Duplicates

One of the most common production issues is duplicate data.

Step 1: Identify Duplicates

db.records.aggregate([
  {
    $group: {
      _id: "$id",
      count: { $sum: 1 },
      docs: { $push: "$_id" }
    }
  },
  { $match: { count: { $gt: 1 } } }
])

Step 2: Remove Duplicates (Keep One)

db.records.aggregate([
  {
    $group: {
      _id: "$id",
      ids: { $push: "$_id" },
      count: { $sum: 1 }
    }
  },
  { $match: { count: { $gt: 1 } } }
]).forEach(doc => {
  doc.ids.shift(); // keep first document
  db.records.deleteMany({
    _id: { $in: doc.ids }
  });
});

Creating Indexes

Indexes improve performance and enforce constraints.

Create Unique Index

db.records.createIndex({ id: 1 }, { unique: true })

View Indexes

db.records.getIndexes()

Best Practices

Always take a backup before:

  • Bulk delete operations
  • Data migration
  • Index changes

Test queries before execution:

// First check what will be affected
db.users.find({ age: { $lt: 20 } })

Use limits when unsure:

db.users.find().limit(5)

Common Mistakes

  • ❌ Running delete without a filter
    db.users.deleteMany({}) // deletes EVERYTHING
    
  • ❌ Forgetting to create a unique index before merging data
  • ❌ Using the Aggregation tab for scripting (doesn't support loops)


If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment