Mango DBLesson 8 – MongoDB Compass & Shell | Dataplexa

MongoDB Compass & Shell

MongoDB gives you two powerful tools to interact with your data outside of your application code — MongoDB Compass, a visual GUI for exploring and querying data without writing a single line of code, and mongosh, the modern interactive shell for running queries, scripts, and administrative commands directly from your terminal. Every serious MongoDB developer uses both — Compass for exploration and visualisation, mongosh for precision and automation.

This lesson covers installing and navigating Compass, using mongosh effectively, and applying both tools to the Dataplexa Store dataset you imported in Lesson 6.

MongoDB Compass — The Visual GUI

MongoDB Compass is a free, official desktop application that lets you connect to any MongoDB instance, browse databases and collections, run queries with a visual filter builder, inspect documents, create indexes, and analyse schema — all without writing code.

Why it exists: not every team member is comfortable with a command-line shell. Compass makes MongoDB accessible to developers, data analysts, and non-technical team members alike. Even experienced developers use it to visually inspect data during debugging and development.

Real-world use: a backend developer uses Compass to verify that documents were inserted correctly, a data analyst explores the schema of an unfamiliar collection, and a DBA inspects index usage and query performance — all in the same tool.

Download MongoDB Compass free from the official page below.

Connecting Compass to Your Database

Once installed, Compass needs a connection string to know which MongoDB server to connect to — local or Atlas.

# Compass connection strings — paste into the Compass connection bar

# Local MongoDB (default — no authentication)
local_connection = "mongodb://localhost:27017"

# Local MongoDB with authentication
local_auth = "mongodb://username:password@localhost:27017"

# MongoDB Atlas (SRV format — replace with your actual URI)
atlas_connection = "mongodb+srv://youruser:yourpassword@cluster0.xxxxx.mongodb.net/"

# Connection steps in Compass:
steps = [
    "1. Open MongoDB Compass",
    "2. Paste your connection string into the URI field",
    "3. Click 'Connect'",
    "4. Browse your databases in the left panel",
    "5. Click 'dataplexa' → select a collection → explore documents",
]

for step in steps:
    print(step)
1. Open MongoDB Compass
2. Paste your connection string into the URI field
3. Click 'Connect'
4. Browse your databases in the left panel
5. Click 'dataplexa' → select a collection → explore documents
  • Compass saves connections — you never need to re-type the URI after the first connect
  • For Atlas, use the full SRV URI from the Atlas Connect dialog (Lesson 7)
  • Compass works with local, Atlas, and any remote MongoDB instance reachable on the network

Navigating the Compass Interface

Compass is organised into tabs — each one gives you a different view of your data and cluster.

# Compass interface — key tabs and what they do

compass_tabs = {
    "Documents": (
        "Browse, filter, insert, edit, and delete documents visually. "
        "Use the filter bar to write MQL queries with autocomplete."
    ),
    "Aggregations": (
        "Build aggregation pipelines stage by stage with a visual editor. "
        "Each stage shows a live preview of its output — no guessing."
    ),
    "Schema": (
        "Analyse the structure of a collection automatically. "
        "Shows field types, value distributions, and cardinality across all documents."
    ),
    "Indexes": (
        "View existing indexes, create new ones, and see index usage statistics. "
        "Helps identify missing indexes causing slow queries."
    ),
    "Explain Plan": (
        "Run a query and see exactly how MongoDB executed it — "
        "which indexes were used, how many documents were scanned."
    ),
    "Validation": (
        "Create and manage JSON Schema validation rules for a collection "
        "directly from the UI."
    ),
}

for tab, description in compass_tabs.items():
    print(f"[{tab}]\n  {description}\n")
[Documents]
Browse, filter, insert, edit, and delete documents visually.

[Aggregations]
Build aggregation pipelines stage by stage with a visual editor.

[Schema]
Analyse the structure of a collection automatically.

[Indexes]
View existing indexes, create new ones, and see usage statistics.

[Explain Plan]
Run a query and see exactly how MongoDB executed it.

[Validation]
Create and manage JSON Schema validation rules from the UI.
  • The Schema tab is invaluable when working with an unfamiliar dataset — it reveals field names, types, and value distributions at a glance
  • The Explain Plan tab shows whether a query used an index (IXSCAN) or a full scan (COLLSCAN) — essential for performance tuning
  • The Aggregations tab lets you build and test pipelines interactively before writing them in code

Querying with Compass — Using the Filter Bar

The Documents tab has a filter bar that accepts standard MQL filter syntax. You type a query object and Compass returns matching documents instantly.

# Compass filter bar examples — paste these into the Filter input

# All premium users
filter_1 = '{ "membership": "premium" }'

# Products priced over $50 in the Electronics category
filter_2 = '{ "category": "Electronics", "price": { "$gt": 50 } }'

# Orders with status "delivered"
filter_3 = '{ "status": "delivered" }'

# Users from the UK aged 25 or over
filter_4 = '{ "country": "UK", "age": { "$gte": 25 } }'

# Products with "bestseller" in their tags array
filter_5 = '{ "tags": "bestseller" }'

filters = [filter_1, filter_2, filter_3, filter_4, filter_5]
labels  = ["Premium users", "Electronics > $50", "Delivered orders", "UK users 25+", "Bestseller products"]

for label, f in zip(labels, filters):
    print(f"{label}:\n  {f}\n")
Premium users:
{ "membership": "premium" }

Electronics > $50:
{ "category": "Electronics", "price": { "$gt": 50 } }

Delivered orders:
{ "status": "delivered" }

UK users 25+:
{ "country": "UK", "age": { "$gte": 25 } }

Bestseller products:
{ "tags": "bestseller" }
  • Compass filter syntax is identical to PyMongo / mongosh MQL — what you learn in one applies everywhere
  • Use the Project field in Compass to choose which fields to display in results
  • Use the Sort field to order results — e.g. { "price": -1 } for descending price

mongosh — The Modern MongoDB Shell

mongosh (MongoDB Shell) is the official interactive shell for MongoDB, replacing the older mongo shell. It is built on Node.js, supports modern JavaScript including async/await, has autocomplete and syntax highlighting, and can run script files. It is the tool of choice for running queries, performing administrative tasks, and scripting database operations.

# mongosh — connecting and essential navigation commands

# Connect to local MongoDB
# mongosh

# Connect to Atlas
# mongosh "mongodb+srv://youruser:yourpassword@cluster0.xxxxx.mongodb.net/"

# ── Navigation ──────────────────────────────────────────
# show dbs                     list all databases
# use dataplexa                switch to the dataplexa database
# show collections             list all collections in current database
# db                           print the current database name

# ── Collection info ─────────────────────────────────────
# db.products.countDocuments()            count all documents
# db.products.countDocuments({category:"Electronics"})  count with filter
# db.products.stats()                     collection statistics
# db.products.getIndexes()                list indexes

# ── Quick data checks ───────────────────────────────────
# db.products.findOne()                   return one document
# db.products.find().limit(3)             return first 3 documents
# db.products.distinct("category")        list unique category values

print("mongosh commands ready — run them in your terminal after connecting")
mongosh commands ready — run them in your terminal after connecting
  • mongosh has tab autocomplete — press Tab after db. to see available collections and methods
  • db.collection.findOne() is the fastest way to inspect a sample document and understand the schema
  • db.collection.distinct("field") instantly shows all unique values for a field — useful for understanding data variety

Exploring the Dataplexa Dataset in mongosh

Now that your dataset is imported, use mongosh to explore it. These commands give you a complete picture of what is in the database before writing any application code.

# Explore the Dataplexa Store dataset — run in mongosh

# Switch to the course database
# use dataplexa

# Check what collections exist
# show collections

# Count documents in each collection
# db.users.countDocuments()       → 5
# db.products.countDocuments()    → 7
# db.orders.countDocuments()      → 7
# db.reviews.countDocuments()     → 5

# Inspect a sample document from each collection
# db.users.findOne()
# db.products.findOne()
# db.orders.findOne()
# db.reviews.findOne()

# Explore unique values
# db.products.distinct("category")   → ['Electronics', 'Furniture', 'Stationery']
# db.orders.distinct("status")       → ['cancelled', 'delivered', 'processing', 'shipped']
# db.users.distinct("membership")    → ['basic', 'premium']
# db.users.distinct("country")       → ['Germany', 'Spain', 'UK', 'USA']

print("Dataset exploration commands ready — run each line in mongosh")
Collections: users, products, orders, reviews

Document counts:
users → 5
products → 7
orders → 7
reviews → 5

Product categories: ['Electronics', 'Furniture', 'Stationery']
Order statuses: ['cancelled', 'delivered', 'processing', 'shipped']
Memberships: ['basic', 'premium']
User countries: ['Germany', 'Spain', 'UK', 'USA']
  • Always start a new project by exploring the schema with findOne() and distinct() — understand your data before querying it
  • distinct() is faster than find() for getting a summary of field values
  • mongosh outputs documents as formatted JSON — much easier to read than raw text

Running Script Files with mongosh

mongosh can run JavaScript files directly — useful for repeatable setup scripts, bulk data operations, and automated database tasks.

# Running a script file with mongosh

# Create a file called explore.js:
script_content = """
// explore.js — run with: mongosh explore.js

const db = connect("mongodb://localhost:27017/dataplexa");

print("=== Dataplexa Store Summary ===");
print("Users:    ", db.users.countDocuments());
print("Products: ", db.products.countDocuments());
print("Orders:   ", db.orders.countDocuments());
print("Reviews:  ", db.reviews.countDocuments());

print("\\nProduct categories:");
db.products.distinct("category").forEach(cat => print("  -", cat));

print("\\nOrder statuses:");
db.orders.distinct("status").forEach(s => print("  -", s));
"""

# Run the script from your terminal:
# mongosh explore.js

print("Script written — run with: mongosh explore.js")
=== Dataplexa Store Summary ===
Users: 5
Products: 7
Orders: 7
Reviews: 5

Product categories:
- Electronics
- Furniture
- Stationery

Order statuses:
- cancelled
- delivered
- processing
- shipped
  • Run a script with mongosh scriptname.js — no interactive prompt, runs and exits
  • Scripts are plain JavaScript — you can use loops, conditionals, functions, and all ES6+ features
  • Use scripts for database setup, seed data insertion, and scheduled maintenance tasks

Compass vs mongosh — When to Use Each

Task Best Tool Why
Browse documents visually Compass Formatted, paginated, easy to navigate
Analyse schema and field types Compass Schema tab builds a visual report automatically
Build aggregation pipelines Compass Visual stage editor with live previews
Run quick ad-hoc queries mongosh Faster than opening a GUI for simple lookups
Administrative tasks mongosh Full access to admin commands and replica set ops
Repeatable scripts mongosh Run .js files for automation
Performance / Explain Plan Both Compass has a visual explain; mongosh has .explain()

Practice Questions

Practice 1. What Compass tab automatically analyses the fields, types, and value distributions of a collection?



Practice 2. What mongosh command returns all unique values for the category field in the products collection?



Practice 3. How do you run a JavaScript file called setup.js using mongosh?



Practice 4. What does the Explain Plan tab in Compass help you identify?



Practice 5. What is the Compass filter syntax to find all products in the Electronics category with a rating above 4.5?



Quiz

Quiz 1. Which Compass tab lets you build and test aggregation pipelines with a live stage-by-stage preview?






Quiz 2. What technology is mongosh built on?






Quiz 3. What does COLLSCAN mean in a MongoDB Explain Plan?






Quiz 4. Which mongosh command lists all collections in the currently selected database?






Quiz 5. What is the main advantage of using Compass over mongosh for exploring an unfamiliar dataset?






Next up — Databases, Collections & Documents: the three-level hierarchy that organises all data in MongoDB.