Skip to content

Practice examples of MongoDB CRUD, Aggregation-pipeline, and Index operations using MongoDB Playground in VS Code (connected to localhost).

Notifications You must be signed in to change notification settings

Rajsingh704596/mongodb-playground-examples

Repository files navigation

MongoDB Playground Examples - Beginner Friendly Guide

This repository contains MongoDB Playground scripts tested in VS Code.
It helps you learn MongoDB step by step with examples and explanations.


Table of Contents

  1. What is MongoDB?
  2. Key Components
  3. Installing MongoDB
  4. Basic Mongo Shell Commands
  5. CRUD Operations
  6. Aggregation Framework
  7. Indexing
  8. How to Run

What is MongoDB?

  • MongoDB is a NoSQL database.
  • It stores data in JSON-like documents (actually BSON).
  • Unlike SQL databases, MongoDB does not use tables and rows, but collections and documents.

Example Document:

{
  "name": "Alice",
  "age": 25,
  "city": "Delhi"
}

Explanation:

  • Each document is like a record.
  • A collection is like a table.

Key Components

Component Description
mongod Mongo Daemon is mongoDB server engine. Stores data, handles queries, indexes, and connections. Usually runs automatically in background as a service in modern setups.
mongosh MongoDB shell. Command-line interface to run queries.
MongoDB Compass GUI tool to visualize data, run queries, and analyze performance. Connects to mongod automatically.

💡 Tip: Beginners can start with MongoDB Compass to see documents visually.


Installing MongoDB

  1. Go to MongoDB Community Download.
  2. Download Community Edition for your OS.
  3. Install following instructions.
  4. Start the server using:
mongod
  1. Open a new terminal for the shell:
mongosh

Basic Mongo Shell Commands

Command Explanation Example
show dbs Lists all databases show dbs
use <dbName> Switch or create a database use ecommerce
show collections Lists collections in current DB show collections
db.dropDatabase() Deletes current database db.dropDatabase()

CRUD Operations

CRUD = Create, Read, Update, Delete

1. Create (Insert)

// Insert one document
db.users.insertOne({
  name: "Alice",
  age: 25,
  city: "Delhi",
});

// Insert many documents
db.users.insertMany([
  { name: "Bob", age: 28, city: "Mumbai" },
  { name: "Charlie", age: 30, city: "Bangalore" },
]);

Explanation:

  • insertOne adds one document.
  • insertMany adds multiple documents at once.

Expected Output:

{
  "acknowledged": true,
  "insertedId": ObjectId("...")
}

2. Read (Query)

// Find all documents
db.users.find();

// Find users in Delhi
db.users.find({ city: "Delhi" });

// Find specific fields
db.users.find({}, { name: 1, city: 1 });

// Comparison operators
db.users.find({ age: { $gt: 25 } }); // age > 25
db.users.find({ age: { $lte: 30 } }); // age <= 30

Explanation:

  • { city: "Delhi" } is a filter.
  • { name: 1, city: 1 } shows only name and city fields.
  • $gt = greater than, $lte = less than or equal.

Expected Output:

[
  { "name": "Bob", "city": "Mumbai" },
  { "name": "Charlie", "city": "Bangalore" }
]

3. Update

// Update one document
db.users.updateOne({ name: "Alice" }, { $set: { city: "Noida" } });

// Update multiple documents
db.users.updateMany({ city: "Mumbai" }, { $set: { verified: true } });

Explanation:

  • $set changes or adds fields.
  • updateOne updates the first matching document.
  • updateMany updates all matching documents.

Expected Output:

{
  "acknowledged": true,
  "modifiedCount": 1
}

4. Delete

// Delete one
db.users.deleteOne({ name: "Charlie" });

// Delete many
db.users.deleteMany({ verified: false });

Explanation:

  • Deletes documents matching the filter.

Expected Output:

{ "acknowledged": true, "deletedCount": 1 }

Aggregation Framework

Used for advanced data analysis (like SQL GROUP BY).

db.orders.aggregate([
  { $match: { status: "delivered" } },
  {
    $group: {
      _id: "$customerId",
      totalAmount: { $sum: "$amount" },
      orderCount: { $sum: 1 },
    },
  },
  { $sort: { totalAmount: -1 } },
]);

Explanation:

  1. $match filters documents.
  2. $group groups by customerId and calculates totals.
  3. $sort sorts by totalAmount descending.

Indexing

// Single-field index
db.users.createIndex({ name: 1 });

// Compound index
db.users.createIndex({ city: 1, age: -1 });

// List indexes
db.users.getIndexes();

// Drop an index
db.users.dropIndex("name_1");

Tip: Use indexes on fields you search or sort frequently. Avoid indexing highly updated fields.


How to Run

  1. Open .mongodb.js file in VS Code.
  2. Click Run Playground.
  3. Or use mongosh manually to run commands.
  4. Visualize results using MongoDB Compass.

About

Practice examples of MongoDB CRUD, Aggregation-pipeline, and Index operations using MongoDB Playground in VS Code (connected to localhost).

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published