Beginner

Up and Running with MongoDB for Data Analysts

running · mongodb · data · analysts · nosql · databases · sql · shell · compass · atlas · commands · exploring · collection · crud · documents · performance · schema · types · aggregation...

Table of Contents

  1. Module 1 — Understanding the structure and role of MongoDB in analytics
  1. Module 2 — Installation and navigation in MongoDB with Compass and the Shell
  1. Module 3 — Data exploration and querying in MongoDB
  1. Demo Files and Code Examples
  1. Summary and key points

1. Understand the structure and role of MongoDB in analytics


1.1 MongoDB for Data Analysts

This course is for data analysts who want to learn about MongoDB. Even if your background is entirely SQL oriented, this course is designed to help you feel comfortable with the MongoDB document model.

The initial question is simple: what happens when your data no longer fits the stereotype? When every row is slightly different and every update breaks your schema? This is precisely when it’s time to try something designed for change, like MongoDB.


1.2 The modern data challenge

The SQL world and its limits

In the SQL world, we are used to structure: tables, joins, rigid schemas, one-to-many relationships, and neat columns. But today’s data isn’t always so cooperative.

In the modern world, we find:

  • clickstreams: massive behavior logs, each with slightly different metadata.
  • IoT data streaming from devices that send different values ​​at different times.
  • Often nested JSON blobs, often inconsistent.
  • Data that varies from record to record: one user may have two addresses, another none.
  • arrays, nested objects, or fields that change from week to week — semi-structured or sometimes not structured at all.

Why MongoDB?

We live in a world of humongous data: clickstreams, logs, IoT devices — massive, fast-moving, and often unpredictable data. To manage humongous data, you need a humongous database. And if we just take a slice of the two words humongous and database, we get the name MongoDB. This isn’t a reference to a sci-fi hero or villain — it’s an homage to the platform’s original mission: to manage massive amounts of rapidly changing data without slowing down.

The three pillars of MongoDB

MongoDB is a document-based database. Instead of storing data in rigid tables with rows and columns, it stores information in rich, flexible documents — a bit like JSON. Each document can contain all the associated data you need, nested, even structured differently from document to document.

PillarDescription
VersatileWhether product catalogs, web events or IoT signals, MongoDB adapts to the shape of your data. No need to force everything into a fixed schema from the start, it grows and evolves with your dataset.
ScalableMongoDB was designed for high-volume distributed systems. As your data grows, MongoDB can scale horizontally, handling more load without collapsing.
FastNo need to write five joins to build a customer profile — a single document already contains everything.

Why should analysts care?

MongoDB delivers exactly what we want in the real world:

  1. Speed — You don’t write five joins to assemble a customer profile. One document is enough and everything is already there.
  2. Flexibility — You are not blocked when data changes. Add a new field, no problem. Store an array instead of a string — MongoDB won’t complain.
  3. Usability — You can explore documents live immediately, without requiring an engineer to migrate the schema, create new views, or clean up the source.

Instead of designing around limitations, you work with your data as it is — and that’s a big change in how quickly you can move from raw data to insights.


1.3 Building blocks: Databases, Collections and Documents

Comparing SQL vs MongoDB

If you’re coming from SQL, here’s a quick comparison to make the transition easier:

SQLMongoDB
DatabaseDatabase
TableCollection
RowDocument
ColumnField
Foreign key / JOINEmbedded object

The folder system metaphor

Think of MongoDB as an intelligent folder system:

  • At the top level, you have a database.
  • In this database, you create collections — a bit like folders.
  • In each collection, you store documents — like individual files, each containing all the data for a single entity.

Concrete example: the users collection

// Document d'Ana
{
  "name": "Ana",
  "email": "ana@example.com",
  "location": {
    "city": "Austin",
    "country": "USA"
  },
  "interests": ["analytics", "hiking"]
}

// Document de Rob (structure différente — totalement valide)
{
  "name": "Rob",
  "email": "rob@example.com",
  "age": 34,
  "subscribed": true
}

This document represents Ana. You have their name, their email, and a nested location object that includes the city and country. You also have an array of interests. Everything about Ana lives in this one document. No need to spread the data across three tables and then join them.

Rob’s document does not include rentals. It instead includes age and subscribed — fields that Ana’s document did not have. This is completely valid. MongoDB does not require that every document in a collection follow the exact same structure. One may have 5 fields, the next 10.

For analytics, it’s wonderful. This means that one can start exploring and analyzing before the diagram is finalized. You don’t have to wait for a perfect model — you can work with the data you have, now, immediately.


1.4 How MongoDB stores data: BSON

JSON vs BSON

MongoDB works with JSON, but not directly. It uses a format called BSON (Binary JSON, or more precisely, Binary JavaScript Object Notation). Think of it as JSON’s high-performance cousin.

Why does MongoDB use BSON?

AdvantageDetail
More data typesBSON supports dates, binary data, and special types like ObjectIds — things that don’t exist in vanilla JSON.
Faster read/writeBeing binary makes it easier for the engine to parse and write it. This gives MongoDB a performance advantage, especially at scale.
Embedded metadataEach entry includes metadata like total length and type, which allows MongoDB to optimize queries and indexing in the background.

The role of the MongoDB driver

How does this conversion occur? This is where the MongoDB driver comes in. When your application sends data to MongoDB (generally in the form of a JavaScript object or a Python dictionary), the driver is responsible for converting this JSON into BSON before storing it in the database. You don’t have to write this BSON yourself — everything happens behind the scenes.


1.5 Common data types in MongoDB

A data type defines the type of value a field can contain — a number, a date, a list. Here are the main types encountered in MongoDB:

The three basic types

TypeDescriptionExample
StringText used for names, labels, etc."Ana"
NumberIntegers or decimals for counting, scoring, etc.42
BooleanTrue/false value for toggles, flags, yes/no questionstrue or false

Advanced types

TypeDescription
Date / TimestampTo track when something was created, updated or saved. These are not simple strings — they are date objects. You can sort them, filter them, and even calculate differences between them.
ArrayAllows you to store several values ​​in a single field (eg: the tags of a blog article or the interests of a user). No need to create a separate table or relationship — we just use brackets.
Embedded DocumentStructures within other structures. For example, a user’s location might include a city and a country. Rather than splitting this over several tables, we nest the mini-document directly into the main one.
ObjectIdEach MongoDB document has a unique identifier called ObjectId. It is a 12 byte type that includes information such as the creation timestamp. MongoDB generates it automatically.

Complete example with all types

{
  "name": "Ana",                          // String
  "email": "ana@example.com",            // String
  "active": true,                         // Boolean
  "signedDate": { "$date": "2024-01-15T00:00:00Z" }, // Timestamp
  "tags": ["analytics", "pro_user"],     // Array
  "location": {                           // Embedded Document
    "city": "Austin",
    "coordinates": [30.2672, -97.7431]   // Array dans un Embedded Document
  }
}

A single compact document capturing multiple types of data, all organized in a readable and flexible structure. No joins, no schema migrations, no surprises.


1.6 Schema flexibility and denormalization

Schema Flexibility

In traditional databases, each record in a table follows the same structure. Each row must have the same columns, even if some are always empty or contain null.

MongoDB takes a different approach. Two documents can live in the same collection and look completely different — and that’s not a bug, it’s a feature.

// Ana — a name et city
{ "name": "Ana", "city": "Austin" }

// Rob — a age et subscribed, mais pas de city
{ "name": "Rob", "age": 34, "subscribed": true }

// Lena — a email et un location imbriqué
{ "name": "Lena", "email": "lena@example.com", "location": { "city": "Dallas" } }

All three live peacefully in the same collection. No migrations, no broken queries, no drama.

Denormalization

In SQL, we normalize the data: we distribute them over several tables, then we put them back together with joins. This is great for consistency, but not nice for fast queries.

In MongoDB, we do the opposite: we denormalize — we store everything related in a single document.

// Document de commande dénormalisé
{
  "order_id": "ORD-2024-001",
  "total": 129.99,
  "customer": {
    "name": "Ana",
    "email": "ana@example.com"
  },
  "items": [
    { "product": "Clavier", "qty": 1, "price": 79.99 },
    { "product": "Souris", "qty": 1, "price": 49.99 }
  ]
}

No joins, no foreign keys — just one read and you have all the context you need.

Why is this useful for analytics?

  1. You don’t need to migrate a schema just to add a new field — edit when you need to and move on.
  2. You can embed contextually related data — no need to search for it elsewhere.
  3. Your queries become simpler. You don’t need complex logic to reassemble the story — you’re reading it straight from the source.

1.7 Analytical use cases for MongoDB

MongoDB is a great option when analytics meets real-world data, especially the kind that is anything but tidy.

Where MongoDB excels

Use casesWhy MongoDB fits it
Web activity trackingClicks, page views, mouse movements — each slightly different, each arriving quickly. MongoDB absorbs this variation and keeps pace.
IoT sensor dataDevices do not ask permission to change formats or send sporadic updates. MongoDB allows you to capture everything without forcing it into meaningless rows and columns.
Product catalogsSome items have three prices, others have size charts, colors, regional restrictions. MongoDB lets you store all of this directly in a document.
User-generated contentReviews, comments, personalized profiles — each user adds their own flavor of data. MongoDB does not object.

When does MongoDB make the most sense?

  • When the structure varies from one record to another.
  • When your data volume is high and growing quickly.
  • When your relationships are simple and don’t require dozens of foreign keys.
  • When speed is important and you can’t wait for a batch job or a 5-table join.
  • When the schema is not fully defined from the start.

In short: MongoDB meets analysts where they are — working with messy, scalable, high-volume data — and helps them gain insights faster.


1.8 MongoDB and exploratory analysis

Exploratory analysis does not start with a perfect schema. It starts with a question — sometimes just a hunch or curiosity. And to follow that curiosity, you need a database that doesn’t hold up when things aren’t perfectly structured. This is where MongoDB fits in perfectly.

The flow of exploratory analysis

  1. Raw data — just what you have on hand.
  2. The question — “What is happening here? Is this a trend?”
  3. Filtering — isolate what matters.
  4. Summary — maybe decide to model it later.

It’s fast, it’s flexible, and it requires tools that don’t get in the way. MongoDB lets you move from messy data to meaningful insights without having to file a ticket to restructure the schema.


1.9 Responsibilities of the analyst vs. the engineer

When the data disappears, call the engineer. When the insight disappears, call the analyst. It’s a perfect balance: while engineers structure and load data, analysts help turn it into answers.

Who does what in a MongoDB project?

RoleResponsibilities
AnalystWriting simple queries, data exploration, construction of dashboards and reports, creation of aggregation pipelines.
EngineerSchema design, data injection, index management, and more complex querying tasks.

Collaboration in action

Example 1: An analyst notices that a query is slow and contacts the engineer. The engineer notices that the query could benefit from indexing — and just like that, performance improves.

Example 2: The analyst builds an aggregation pipeline and comes across a tricky edge case. A quick discussion with the engineer leads to a better approach — flattening fields to clean them.

This back and forth isn’t just a technical question, it’s teamwork. And when analysts and engineers support each other, insights arrive faster and frustration takes a backseat.


2. Installing and navigating MongoDB with Compass and the Shell


2.1 Demo: Installing MongoDB, Compass and Shell

Install MongoDB Community Server

  1. Visit the official MongoDB website to download MongoDB Community Server — the free and powerful edition designed for developers, analysts and curious minds.
  2. Select the latest version, choose the platform (Windows 64-bit in this demonstration), and download the installer.
  3. Launch the MongoDB installer — it’s a straightforward wizard.
  4. Click Next, review the license agreement, and choose the Complete setup option (includes all program features).
  5. Important: Check the box to install MongoDB Compass at the same time — the official MongoDB GUI. It’s like setting up the coffee and the cup at the same time.
  6. Continue through the service configuration (accept the defaults unless required), then click Install.
  7. Once installation is complete: MongoDB and Compass are ready to use.

Install MongoDB Shell (mongosh) separately on Windows

Unlike Compass, the shell must be downloaded separately on Windows:

  1. Return to the MongoDB site, navigate to the Tools section, and find MongoDB Shell.
  2. Select the correct version and type of installer, download and run the setup.
  3. Go through the wizard steps, confirm the installation location.

Verify installation

Open PowerShell or a command prompt and type:

mongosh

If you see the version numbers and the login message, everything is working as expected. You may see a warning that access control is not enabled — this is standard for local development and poses no problem at this stage.


2.2 Demo: Exploring and customizing the MongoDB Compass interface

Interface Tower

At launch, Compass presents a clean home screen with:

  • A green Add new connection button in the center.
  • A side panel on the left that lists your saved connections.
  • A toolbar at the top with the usual menus: Connections, Edit, View, Help.

Useful shortcuts in the View menu:

  • Ctrl + =: Zoom in
  • Ctrl + -: Zoom out
  • Ctrl + 0: Reset zoom

Settings (gear icon)

Clicking on the gear icon on the left takes you to a customizable toolkit.

General tab:

  • Read-only mode: Navigate without the risk of accidentally modifying anything.
  • MongoDB Shell integration in Compass: A checkbox to activate it.
  • Protection of sensitive connection strings: A simple toggle.
  • Default query sort: Choose to see documents in natural order or sorted by ID (ascending/descending).
  • Support for Kerberos authentication.

Theme tab:

  • Two options: Dark or Light, with possibility to synchronize with the operating system.

Privacy tab:

  • Enable automatic updates.
  • Allow geographic visualization.
  • Send usage statistics (optional, explained clearly).

Proxy configuration tab:

  • For those who work behind firewalls or in corporate networks.
  • Options: system proxy, manual, or hosts that bypass the proxy.

OIDC (OpenID Connect) tab:

  • Useful for connecting to MongoDB Atlas with secure token-based logins.

Artificial Intelligence tab:

  • Enables AI capabilities to generate queries or build aggregations in natural language.
  • Requires connection to MongoDB Atlas.

Explore an existing collection

  1. In the side panel, click Connect next to localhost.
  2. The database structure appears: admin, config, local, and the SQL Authority database already configured for the demonstration.
  3. Expanding the database reveals the employees collection.
  4. The Documents tab displays two example records: Alice (HR) and Bob (Finance).

Tabs available in a collection:

TabFeature
DocumentsDisplaying documents in map, JSON, or table mode (spreadsheet-style).
AggregationConstruction of pipelines stage by stage, visually or in text mode.
DiagramData analysis: fields, types, visual distributions (histograms).
IndexesOverview of existing indexes, creation of new indexes.
ValidationDefinition of rules to enforce the structure (e.g. mandatory fields).

Data export: Simply click on Export data to export the results of a query or the entire collection in JSON or CSV.


2.3 Demo: Connecting to a database with Compass

Actions available on a connection

Right-clicking on the connected server opens a context menu which allows you to:

  • View performance metrics.
  • Refresh database.
  • Copy connection string (to share with a colleague).
  • Show connection info (Show connection info): connection status, hostname, cluster type, MongoDB version.

Color coding of connections

Open the Edit connection panel and assign a color code (orange, purple, etc.) to the connection. It’s not just cosmetic — it’s a smart safety feature. Seeing orange may remind you: “Be careful, this is production, no testing here.”

Create database and collection

  1. Click on the Create database button.
  2. A dialog box appears to name the database (PS) and the collection (users).
  3. Additional options available:
  • Support time series (for sensor type data).
  • Collation (language-specific sorting rules).
  • Clustered collections.
  1. Click on Create database — the database instantly appears in the side panel.

Insert documents

  1. Click on Add data > Insert document.
  2. A JSON editor opens:
// Insérer Ana
{
  "name": "Ana",
  "location": "Austin, USA",
  "interests": ["analytics", "hiking"]
}

// Insérer Rob
{
  "name": "Rob",
  "age": 34
}
  1. After insertion, switch to Tabular view for a spreadsheet-style display — each field in the document is presented in columns, tables like interests are also expanded into columns.

2.4 Demo: Exploring and connecting with MongoDB Shell (mongosh)

Launch Shell and Login

Launch the Shell simply by typing mongosh in the terminal. The Shell automatically connects to the local instance and displays the MongoDB and MongoShell versions.

Note: The yellow warning that access control is not enabled is perfectly normal for local development.

Essential navigation commands

// Lister toutes les bases de données disponibles
show dbs

// Basculer vers la base de données PS
use PS

// Afficher toutes les collections dans la base de données PS
show collections

// Récupérer le premier document de la collection users
db.users.findOne()

// Afficher tous les documents de la collection users
db.users.find().pretty()

Queries with filters

// Trouver les users abonnés ET âgés de plus de 30 ans
db.users.find({
  subscribed: true,           // Filtre sur les utilisateurs abonnés
  age: { $gt: 30 }            // Filtre sur les utilisateurs de plus de 30 ans
}).pretty()

// Trouver les documents où le champ "age" n'existe pas
db.users.find({
  age: { $exists: false }     // Filtre sur les documents sans champ "age"
}).pretty()

Expected results:

  • Query with subscribed: true and age > 30 returns Rob.
  • Query with age: { $exists: false } returns Ana (its document has no age field).

These types of existence checks are incredibly useful when your schema is flexible or when you are cleaning up inconsistencies.

Shell Shortcuts

ShortcutAction
/ Navigate Order History
Ctrl + LClear screen

2.5 Comparing Compass vs Shell for Analytical Workflows

Comparative summary

CriterionCompass (GUI)MongoShell (CLI)
NavigationVisual, click-friendlyCode-first, no visual navigation
InputMinimalRequired for all orders
Learning curveLowModerate
AutomationNot supportedYes — repeatable scripts
Query constructionVisual AND textCode only
Field Types / SchemaComplete ExperienceLimited support
Export in CSVYesYes
Ideal forQuick exploration, navigation, inspectionRepeated tasks, scripting, debugging

When to use which one?

  • Compass: When you explore a collection, filter documents visually, analyze a schema, or build a first query.
  • Shell: When you write automated scripts, load data, or chain operations into a larger workflow.

Key takeaway: You don’t have to choose one or the other. Use Compass when exploring, and Shell when scripting or digging deeper. It’s not a competition, it’s teamwork.


2.6 Troubleshooting Common Connection Issues

Here are the most common connection errors and how to resolve them:

ErrorProbable causeSolution
”IP address not authorized”Your IP address has not been added to the cloud server’s whitelist.Update Network Access settings in Atlas or firewall rules.
”Authentication failed”Incorrect credentials or nonexistent user.Check credentials, make sure to connect to the correct authentication base, confirm that the user exists on the cluster.
”Invalid connection string”Typo in the URI (missing slash, misspelled parameter, extra colon).Always copy connection strings directly from the source and scan them for anomalies.
”Could not connect to host”Firewall blocking the port. MongoDB typically uses port 27017.Open port or coordinate with IT team.
Timeout / no responseThe server is not started.Check that the MongoDB service is started.

3. Exploring and Querying Data in MongoDB


3.1 Demo: Exploring collections and documents with Atlas

What is MongoDB Atlas?

MongoDB Atlas is the cloud version of MongoDB — like Databricks for Spark or Snowflake for SQL. Instead of managing local servers, installations, and ports, Atlas brings MongoDB to the cloud with far less configuration friction and no infrastructure babysitting.

Setting up an Atlas cluster

  1. Connect to MongoDB Atlas (connection possible via a Google or GitHub account).
  2. On the Clusters tab, create a new cluster.
  3. Choose the cloud provider (AWS, Google Cloud, or Azure) and a geographically close region.
  4. Select the free tier — a shared cluster perfect for development and testing, with no credit card required.
  5. Atlas offers to preload a demo dataset — highly recommended option (movies, users collections, etc.).

Configuring Security

  1. Atlas guides you through configuring authentication.
  2. Choose method username/password, create a database user with read and write access.
  3. Important: These credentials are different from your Atlas login credentials — keep them separate.

Out-of-the-box performance metrics

While the cluster is provisioning, Atlas provides real-time updates and dashboards with:

  • Counters
  • Logical size
  • Connection sets

Everything updates in real time — and it’s always on the free tier.

Query Insights and Performance Advisor

  • Query Insights: Tracks slow queries. Collection-level view of latency to identify which operations are taking time, broken down by namespace.
  • Performance Advisor: Analyzes your workload and suggests indexes. Identifies patterns causing inefficiencies (missing indexes, schema anti-patterns) and offers one-click suggestions.

Connecting Atlas to Compass

  1. In Atlas, click Connect and choose Compass as the access method.
  2. Copy the connection string, update it with your password.
  3. Paste it into Compass — a few clicks later, you’re connected to your cloud-hosted MongoDB.

Exploring the sample_mflix dataset

In Compass, with the Atlas connection established:

  • The admin, local, and sample_mflix databases appear in the side panel.
  • By expanding sample_mflix and opening the movies collection, we arrive at a nice view of rich documents: nested arrays, nested objects, fields like title, release date, genre.
  • This isn’t just a toy dataset — it’s rich, varied, and perfect for learning.

3.2 Demo: Analyzing fields with the Aggregation, Indexing and Validation tabs

Building a visual aggregation pipeline

In the movies collection of sample_mflix (more than 21,000 records):

  1. Switch to the Aggregation tab.
  2. Choose to build the pipeline stage by stage manually (Add Stage mode).

Stage 1: $match — Filter by year

{ year: 1999 }

Compass instantly previews matching documents on the right.

Stage 2: $group — Group by notation and count

{
  _id: '$rated',
  total: { $sum: 1 }
}

Compass refreshes the preview to show grouped results.

Stage 3: $sort — Sort by descending total

{ total: -1 }

With all three stages ($match, $group, $sort) in place, click Run to run the full pipeline. The result: a grouped, counted, and sorted view — a quick answer to the question “What type of content dominated the box office in 1999?”

To export the results, click Export to download as JSON or CSV, or copy the aggregation definition for reuse.

Performance analysis with Explain

  1. Click the Explain button to see what is happening under the hood.
  2. Compass displays a visual execution plan.
  3. Initial result: COLLSCAN — MongoDB scanned all 21,000 documents to return only 8 results. 19 ms processing, 0 indexes used.
  4. Compass displays a warning: “No index available for this query.”

Creating an index to optimize performance

  1. Click on the icon suggested by Compass to open the index creation panel.
  2. Choose the filtered year field and select the ascending type.
  3. Click on Create index.
  4. In the Indexes tab, the new index year appears as the third index (after _id and a compound text index), marked as ready.
  5. Restart the pipeline and click on Explain again: the result changes from COLLSCAN to IXSCAN. MongoDB now uses the index to scan ~500 documents instead of 21,000. Much faster, much more efficient.

Analyzing the schema with the Schema tab

  1. In the Schema tab, click on Analyze Schema.
  2. Compass samples 1,000 documents to build a complete profile.
  3. Displays for each field: name, data type, frequency of appearance, visual distributions of values, array lengths, field-level insights.
  4. For fields like cast, genre, or runtime, Compass shows how the values ​​vary and helps detect outliers or missing values.

Define validation rules with the Validation tab

Compass can auto-generate a validation schema based on existing data. To create a rule manually:

{
  "$jsonSchema": {
    "bsonType": "object",
    "required": ["year"],
    "properties": {
      "year": {
        "bsonType": "int",
        "minimum": 1900,
        "description": "year must be an integer >= 1900"
      }
    }
  }
}

This rule ensures that each document has a year field which is an integer of at least 1900. After defining the rule, click on Preview documents: Compass highlights valid documents in green and invalid documents in red (where year is absent or incorrectly typed). Feedback is instant and actionable.

Note: By applying the rule via Apply, Compass notifies you that it will apply to all future inserts and updates. Existing documents are not affected.


3.3 Demo: Simple data operations with Compass and AI

Direct document editing in Compass

With the movies collection open (more than 21,000 films):

Method 1:

  1. Hover over a document and click Edit.
  2. The document opens in editable format directly in the interface.
  3. Expand fields, modify values ​​(eg year or gender).
  4. Click Update — Compass confirms the change.

Method 2:

  1. Double-click directly on the field to modify.
  2. It becomes editable immediately.
  3. Update the value and click Update.

Other CRUD operations in Compass

OperationHow
Copy to clipboard“Copy” icon next to the document — great for reusing, debugging, or sharing.
CloneCreate a duplicate of the document to edit independently.
DeleteDelete icon on document.

Natural Language Search with AI

Compass incorporates natural language search capabilities, without needing to know MongoDB syntax.

Example 1: Free text query

Display all the movies released in the year 2010

→ Compass converts the phrase to a valid MongoDB query, performs the search, and displays only movies from 2010.

Example 2: Search by keyword in a text field

Show all the titles that contain the word "rich"

→ Compass builds a query with a regular expression (regex) on the title field, with case-insensitive matching. It also finds titles where “rich” is part of a word (e.g. “Richard”).

Example 3: SQL style syntax

SELECT * FROM movies WHERE runtime > 65

→ Compass even interprets this SQL syntax, shows the equivalent MongoDB query, and returns movies longer than 65 minutes.

Note: After execution, Compass may display a “Query executed without index” notification with a one-click Create index button — the built-in performance assistant.


3.4 Demo: Navigating MongoDB Atlas with Shell Commands

Launch Shell from Compass

In Compass, click on the Open MongoDB Shell button — this directly launches mongosh integrated into Compass, connected to the Atlas cluster. The prompt displays the primary node, confirming that we are in a real Atlas environment.

// Lister toutes les bases de données disponibles avec leur taille
show dbs
// Sortie : sample_mflix, admin, local (avec taille de chaque)

// Basculer vers la base de données sample_mflix
use sample_mflix

// Lister toutes les collections
show collections
// Sortie : comments, embedded_movies, movies, sessions, theaters, users

// Récupérer un document de la collection movies (un aperçu brut)
db.movies.findOne()
// Sortie : document avec champs variés, arrays, objets imbriqués

Connect to Atlas via Shell without Compass

If MongoDB Compass is not installed:

  1. In the Atlas dashboard, click on Connect.
  2. Choose Shell as the access method.
  3. Atlas generates the exact mongosh command with the connection string.
  4. Copy this command to your terminal, enter your password, and you are connected.
# Exemple de commande générée par Atlas
mongosh "mongodb+srv://cluster0.xxxxx.mongodb.net/myFirstDatabase" --apiVersion 1 --username <username>

3.5 Demo: Complete CRUD operations with the Shell

Initialization: Insert data with insertMany

// Basculer vers la base de données de travail
use users

// Insérer trois utilisateurs avec insertMany
db.users_demo.insertMany([
  {
    name: "Emily",
    email: "emily@example.com",
    age: 27,
    preferences: {
      theme: "dark",
      notifications: true
    },
    subscribed: true
  },
  {
    name: "Niko",
    email: "niko@example.com",
    age: 35,
    preferences: {
      theme: "light",
      betaOptIn: false
    },
    tags: ["dev", "beta"]
  },
  {
    name: "Logan",
    email: "logan@example.com",
    age: 31,
    subscribed: false
  }
]);
// MongoDB confirme l'insertion et retourne les ObjectIds pour chaque document

READ — Read with filters

// Trouver tous les users qui ont un champ "preferences"
db.users_demo.find({ preferences: { $exists: true } }).pretty();
// Retourne : Emily et Niko

// Trouver les users avec le thème "dark" dans les préférences
db.users_demo.find({ "preferences.theme": "dark" }).pretty();
// Retourne : Emily

Dot notation: The "preferences.theme" notation allows access to fields nested in subdocuments.

UPDATE — Update fields

// Ajouter un objet preferences à Logan (il n'en avait pas)
db.users_demo.updateOne(
  { name: "Logan" },
  { $set: { preferences: { theme: "minimal", notifications: false } } }
);

// Vérifier la mise à jour de Logan
db.users_demo.find({ name: "Logan" }).pretty();

// Mise à jour en masse : activer les notifications pour tous les users avec le thème "light"
db.users_demo.updateMany(
  { "preferences.theme": "light" },
  { $set: { "preferences.notifications": true } }
);

// Vérifier les changements sur les users avec le thème "light"
db.users_demo.find({ "preferences.theme": "light" }).pretty();
// Niko apparaît maintenant avec notifications: true

DELETE — Delete documents

// Supprimer les users qui ont refusé la participation au beta
db.users_demo.deleteMany({ "preferences.betaOptIn": false });
// MongoDB confirme qu'un document a été supprimé (Niko)

// Afficher tous les documents restants
db.users_demo.find({}).pretty();
// Seulement Logan et Emily restent

REPLACE — Replace an entire document

// Remplacer entièrement le profil d'Emily
db.users_demo.replaceOne(
  { name: "Emily" },
  {
    name: "Emily Smith",
    email: "emily.smith@example.com",
    age: 28,
    preferences: {
      theme: "dark",
      notifications: false,
      language: "en-US"
    },
    subscribed: true
  }
);

// Confirmer le remplacement
db.users_demo.find({ name: "Emily Smith" }).pretty();

DROP — Delete an entire collection

// Supprimer la collection users_demo entièrement
db.users_demo.drop();
// MongoDB retourne true — la collection est définitivement supprimée

The complete CRUD cycle: insert → read → update → bulk update → delete → replace → drop, all executed directly from the shell.


3.6 Demo: Scheduling automated tasks with the Shell

Automation isn’t just a show of power — it’s a necessity. This demo shows how to make MongoDB work for you, even when you’re not looking.

The problem to be solved

We want to add a tag: "agecol" field to all users who have an age field in their document. This tag will allow you to filter, analyze, or batch process these records later — without wanting to do it manually each time new users are added.

Step 1: The update JavaScript script

MongoDB Shell natively understands JavaScript. It is the direct scripting language for the Shell.

// Fichier : update_tags.js

// Basculer vers la base de données PS
use('PS');

// Mettre à jour tous les documents où le champ "age" existe
// Ajouter un champ "tag" avec la valeur "agecol"
db.users.updateMany(
  { age: { $exists: true } },   // Filtre : documents avec un champ age
  { $set: { tag: "agecol" } }   // Mise à jour : ajout du tag
);

Possible alternatives: Python with PyMongo, Node.js, or bash scripts — but for direct automation in MongoDB Shell, JavaScript is the most direct route.

Step 2: The batch file (.bat) as trigger

@echo off
:: Fichier : run_tag_task.bat
mongosh D:\data\update_tags.js

This small batch file simply calls mongosh and tells it to run our JavaScript script. It’s a wrapper or trigger that you can double-click, schedule, or run programmatically.

On Mac or Linux: Create a .sh file instead.

Step 3: Scheduling with Windows Task Scheduler

:: Créer la tâche planifiée pour exécuter le script toutes les minutes
schtasks /create /tn "Run_Tag_Task_Every_Minute" /tr "D:\data\run_tag_task.bat" /sc minute /mo 1

:: Vérifier que la tâche est active
schtasks /query /tn "Run_Tag_Task_Every_Minute"

:: Supprimer la tâche planifiée (nettoyage)
schtasks /delete /tn "Run_Tag_Task_Every_Minute" /f

Alternatives depending on OS:

  • Unix/Linux/macOS: Cron jobs
  • Node.js: Background jobs with libraries like node-cron
  • Cloud: Cloud Functions or Azure Functions

Checking in Compass

After the task has been created and executed:

  1. In Compass, filter the collection for documents with tag: "agecol".
  2. The results appear — the task completed successfully, the documents were updated.
  3. Everything happened without manual intervention.

This automation flow combines:

  • A MongoDB update JavaScript script.
  • A batch file as executor.
  • Windows Task Scheduler for timing.

This combination allows you to apply data hygiene rules, run scheduled updates, or prepare data for analytics — without monitoring the shell.


3.7 Origins and ecosystem of MongoDB

Why “Mongo” in MongoDB?

The name is short for humongous (colossal), because Big DB was apparently already taken. The original goal was to manage massive, fast-moving data — and MongoDB still does that without breaking a sweat or breaking a single schema.

What is an ObjectId?

These long “spaghetti” strings aren’t just random. They actually contain the document creation timestamp. You can even extract temporal information from it. The next time someone asks “Who inserted this and when?”, you’ll know — without having to call a detective.

Structure of an ObjectId (12 bytes):

  • 4 bytes: Creation timestamp (seconds since Unix epoch)
  • 5 bytes: Random machine/process identifier
  • 3 bytes: Random incremental counter
// Extraire le timestamp d'un ObjectId
ObjectId("507f1f77bcf86cd799439011").getTimestamp()
// Retourne : ISODate("2012-10-15T21:26:47Z")

What makes MongoDB different

MongoDB doesn’t pester you with rigid tables or fixed schemas. It lets you be yourself: nest your objects, drag arrays, evolve your model on the fly. It’s like database comfort jogging — flexible, comfortable, and surprisingly productive.

MongoDB Atlas in summary

AdvantageDetail
No servers to manageNo configs to obsess over, no infrastructure to monitor.
CompatibilityWorks perfectly with Compass, Shell, and your code.
Free tierGenerous free tier to get started without a credit card.
Built-in observabilityQuery Insights and Performance Advisor included, even on the free tier.

4. Demo files and code samples


4.1 Module 2 — Sample data (2sample.json)

These two documents illustrate the flexibility of the MongoDB schema: Ana has a nested location object and an interests array, while Rob has age and subscribed fields — totally different structure, same collection.

{"name": "Ana", "email": "ana@example.com", "location": {"city": "Austin", "country": "USA"}, "interests": ["analytics", "hiking"]}
{"name": "Rob", "email": "rob@example.com", "age": 34, "subscribed": true}

4.2 Module 2 — Shell Commands (command.txt)

MongoDB Shell commands used in Module 2 demonstrations:

// Afficher toutes les bases de données disponibles sur le serveur MongoDB
show dbs

// Basculer vers la base de données "PS"
use PS

// Afficher toutes les collections (tables) dans la base de données "PS"
show collections

// Trouver et afficher le premier document de la collection "users"
db.users.findOne()

// Trouver et afficher tous les documents de la collection "users" de manière lisible
db.users.find().pretty()

// Trouver tous les documents où "subscribed" est true et "age" est supérieur à 30
db.users.find({
  subscribed: true,           // Filtre pour les users abonnés
  age: { $gt: 30 }            // Filtre pour les users de plus de 30 ans
}).pretty()

// Trouver tous les documents où le champ "age" n'existe pas
db.users.find({
  age: { $exists: false }     // Filtre pour les documents sans champ "age"
}).pretty()

4.3 Module 3 — Sample data (8sample.json / 10sample.json)

These JSON files contain sample documents with varied structures for module 3 demonstrations. They perfectly illustrate the flexibility of the MongoDB schema.

2sample.json (data subset):

{"name": "Ana", "email": "ana@example.com", "location": {"city": "Austin", "country": "USA"}, "interests": ["analytics", "hiking"]}
{"name": "Rob", "email": "rob@example.com", "age": 34, "subscribed": true}

8sample.json (additional data):

{"name": "Lena", "email": "lena@example.com", "location": {"city": "Dallas"}, "interests": ["cycling", "cloud"], "subscribed": false}
{"name": "Mark", "age": 29, "email": "mark@example.com", "signup_date": {"$date": "2024-03-10T10:00:00Z"}}
{"name": "Sanjay", "email": "sanjay@example.com", "location": {"city": "Mumbai", "country": "India"}, "active": true, "tags": ["pro_user", "analytics"], "interests": ["finance", "reading"]}
{"name": "Ava", "email": "ava@example.com", "location": {"city": "New York", "coordinates": [40.7128, -74.006]}, "age": 42, "subscribed": true}
{"name": "Diego", "email": "diego@example.com", "tags": ["beta", "iot"], "age": 36, "active": false}
{"name": "Mai", "email": "mai@example.com", "location": {"city": "Hanoi"}, "signup_date": {"$date": "2024-04-22T15:45:00Z"}, "interests": ["dataviz"]}
{"name": "Leo", "email": "leo@example.com", "location": {"city": "Toronto", "country": "Canada"}, "age": 31, "subscribed": false, "notes": "frequent contributor"}
{"name": "Noah", "email": "noah@example.com", "tags": ["cloud", "data_science"]}

Notable points in this data:

  • Some documents have location with varying subfields (some have country, some don’t).
  • Some have coordinates (array of geographic coordinates).
  • Some have signup_date in $date format (BSON Date type), others do not.
  • Some have tags (array), some have interests (array), some have neither.
  • active is only present on certain documents.
  • This is the perfect illustration of a flexible scheme in practice.

4.4 Module 3 — CRUD and Automation Demo (demo.txt)

This file contains all the code snippets used in the module 3 demonstrations.

Aggregation Pipeline Stages

// Stage 1 : Filtrer les documents de l'année 1999
{ year: 1999 }

// Stage 2 : Grouper par notation et compter chaque groupe
{
  _id: '$rated',
  total: { $sum: 1 }
}

// Stage 3 : Trier les résultats par total décroissant
{ total: -1 }

Schema validation rule ($jsonSchema)

{
  "$jsonSchema": {
    "bsonType": "object",
    "required": ["year"],
    "properties": {
      "year": {
        "bsonType": "int",
        "minimum": 1900,
        "description": "year must be an integer >= 1900"
      }
    }
  }
}

Natural language queries (Compass AI Preview)

// Retourne tous les films sortis en 2010
Display all the movies released in the year 2010

// Retourne les films dont le titre contient le mot "rich"
Show all the titles that contain the word "rich"

// Filtre style SQL pour les films avec un runtime supérieur à 65
SELECT * FROM movies WHERE runtime > 65

Shell commands for Atlas navigation

// Afficher toutes les bases de données disponibles
show dbs;

// Basculer vers la base de données sample_mflix
use sample_mflix;

// Lister toutes les collections
show collections;

// Afficher un document de la collection movies
db.movies.findOne();

Full CRUD Demo (Create, Read, Update, Delete, Replace)

// Basculer vers la base de données de travail
use users;

// Nettoyage : supprimer les anciennes données de démo
db.users_demo.deleteMany({
  name: { $in: ["Emily", "Niko", "Logan", "Emily Smith"] }
});

// 1. CREATE – Insérer des utilisateurs de démo avec et sans préférences imbriquées
db.users_demo.insertMany([
  {
    name: "Emily",
    email: "emily@example.com",
    age: 27,
    preferences: {
      theme: "dark",
      notifications: true
    },
    subscribed: true
  },
  {
    name: "Niko",
    email: "niko@example.com",
    age: 35,
    preferences: {
      theme: "light",
      betaOptIn: false
    },
    tags: ["dev", "beta"]
  },
  {
    name: "Logan",
    email: "logan@example.com",
    age: 31,
    subscribed: false
  }
]);

// 2. READ – Requête sur les users ayant un champ "preferences"
db.users_demo.find({ preferences: { $exists: true } }).pretty();

// Trouver les users avec une valeur spécifique dans un champ imbriqué
db.users_demo.find({ "preferences.theme": "dark" }).pretty();

// 3. UPDATE – Ajouter ou modifier des champs imbriqués

// Ajouter des préférences à Logan
db.users_demo.updateOne(
  { name: "Logan" },
  { $set: { preferences: { theme: "minimal", notifications: false } } }
);

// Vérifier la mise à jour de Logan
db.users_demo.find({ name: "Logan" }).pretty();

// Mettre à jour les notifications pour tous les users avec le thème "light"
db.users_demo.updateMany(
  { "preferences.theme": "light" },
  { $set: { "preferences.notifications": true } }
);

// Vérifier les modifications des users avec le thème "light"
db.users_demo.find({ "preferences.theme": "light" }).pretty();

// 4. DELETE – Supprimer des users basé sur un critère imbriqué

// Supprimer les users qui ont refusé le beta
db.users_demo.deleteMany({ "preferences.betaOptIn": false });

// Afficher tous les documents restants
db.users_demo.find({}).pretty();

// 5. REPLACE – Remplacer entièrement le profil d'Emily
db.users_demo.replaceOne(
  { name: "Emily" },
  {
    name: "Emily Smith",
    email: "emily.smith@example.com",
    age: 28,
    preferences: {
      theme: "dark",
      notifications: false,
      language: "en-US"
    },
    subscribed: true
  }
);

// Confirmer le remplacement
db.users_demo.find({ name: "Emily Smith" }).pretty();

Windows Task Scheduler Commands

:: Créer la tâche planifiée pour exécuter le script toutes les minutes
schtasks /create /tn "Run_Tag_Task_Every_Minute" /tr "D:\data\run_tag_task.bat" /sc minute /mo 1

:: Vérifier l'état de la tâche
schtasks /query /tn "Run_Tag_Task_Every_Minute"

:: Supprimer la tâche planifiée
schtasks /delete /tn "Run_Tag_Task_Every_Minute" /f

5. Summary and key points

What you learned

ConceptTakeaways
MongoDB Data ModelFlexible documents (JSON/BSON type) instead of rigid tables. Each document can have a different structure within the same collection.
BSONMongoDB internal storage binary format. More efficient than JSON, supports more data types (ObjectId, Date, Binary). Managed automatically by the driver.
Data typesString, Number, Boolean, Date/Timestamp, Array, Embedded Document, ObjectId.
Schema FlexibilityNo need to migrate a schema to add a field. Documents in the same collection can have different structures.
DenormalizationStore related data in a single document rather than normalizing it across multiple tables. Simplifies queries, eliminates joins.
Use casesClickstreams, IoT, product catalogs, user-generated content — any high-volumetric data with variable structure.
MongoDB CompassGUI to explore, view, insert, edit, and delete data. Includes visual aggregation, schema analysis, index management, and validation tools.
MongoDB Shell (mongosh)Scriptable CLI interface. Perfect for automation, batch operations, and integration into workflows.
MongoDB AtlasManaged cloud service. Offers free tier, integrated performance metrics, Query Insights, and Performance Advisor.
CRUD OperationsinsertOne, insertMany, find, findOne, updateOne, updateMany, deleteMany, replaceOne, drop.
Aggregation pipeline$match$group$sort — the fundamental trio for analyzing and summarizing data.
IndexingAn index transforms a COLLSCAN into IXSCAN, drastically reducing the number of documents scanned (e.g. from 21,000 to 500).
Schema validation$jsonSchema allows you to enforce rules on future inserts/updates (field types, minimum values, required fields).
AutomationJavaScript script + .bat file + Windows Task Scheduler = unattended automation. Alternatives: cron (Unix), node-cron, cloud functions.
Analyst/engineer collaborationAnalysts write queries and pipelines; engineers manage schema, indexes, and injection. Collaboration is key.

SQL vs MongoDB Comparison — Summary

CriterionSQL (Relational)MongoDB (Documentary)
Storage unitLine (Row)Document (JSON/BSON)
GroupingTableCollection
RelationshipsForeign Keys + JoinsEmbedded Documents or References
DiagramRigid, defined in advanceFlexible, can evolve
Adaptation to variable dataHard (NULL columns)Native (optional fields)
Performance for full readingMultiple joints requiredOne document = all context
ScaleVertical (scale up)Horizontal (scale out)
Ideal forHighly structured data, complex relationshipsSemi-structured data, high volumes, scalable schemas

MongoDB Tools Summary

ToolMain use
mongoshInteractive CLI shell for queries, scripts, automation
MongoDB CompassGUI for exploration, visualization, visual aggregation
MongoDB AtlasManaged cloud platform (free tier available)
MongoDB DriverLibrary in your language (Python, Node.js, Java, etc.) to connect from application code

Search Terms

running · mongodb · data · analysts · nosql · databases · sql · shell · compass · atlas · commands · exploring · collection · crud · documents · performance · schema · types · aggregation · analysis · bson · connecting · delete · navigation

Interested in this course?

Contact us to book it or get a custom training plan for your team.