Showing posts with label MongoDB Examples. Show all posts
Showing posts with label MongoDB Examples. Show all posts

MongoDB Queries Tutorial: Filters and Projections Explained


Finding Documents with Queries: Filters & Projections

A Magical Treasure Hunt in MongoDB : For beginners to Expert Level

Quick Overview: This MongoDB tutorial explains how to find documents using filters and projections. Whether you’re a beginner or an expert, you’ll learn step-by-step query examples using mongosh and MongoDB Compass to search, filter, and display data efficiently.


๐Ÿ“˜ Table of Contents


Imagine you’re in the Hero Academy Library, and you need to find one special book from thousands. You can ask:

  • “Show me all fire heroes.”
  • “Give me only their names and powers.”

In MongoDB, this is called querying! You use filters (what to find) and projections (what to show). This tutorial is a fun treasure hunt, super easy for a student, but packed with pro-level secrets for experts.

We’ll use:

  • Our Hero Academy from before
  • mongosh (command line)
  • MongoDB Compass (click & search)
  • Real images


Part 1: What Are Filters & Projections?

TermReal-Life ExampleMongoDB Meaning
Filter“Find all red toys”Conditions to select documents
Projection“Show only toy name and color”Fields to show or hide

Fun Fact: Filter = “Who to invite?”
Projection = “What info to print on the card?”



Part 2: Sample Data (Let’s Load Our Heroes!)


use heroAcademy
db.heroes.insertMany([
  { name: "Aarav", power: "Super Speed", level: 5, isActive: true, team: "Alpha", skills: ["run", "jump"] },
  { name: "Priya", power: "Invisibility", level: 7, isActive: true, team: "Alpha", skills: ["hide", "sneak"] },
  { name: "Rohan", power: "Fire Control", level: 4, isActive: false, team: "Beta", skills: ["flame", "shield"] },
  { name: "Sanya", power: "Telekinesis", level: 6, isActive: true, team: "Beta", skills: ["lift", "fly"] },
  { name: "Karan", power: "Ice Blast", level: 3, isActive: true, team: "Alpha", skills: ["freeze", "snow"] }
])


Part 3: Basic Filters – “Find Who?”

1. Find All Heroes

db.heroes.find()

→ Shows everything

2. Find Active Heroes

db.heroes.find({ isActive: true })

→ Only heroes with isActive: true
Like: “Show me only students who came to school today.”

3. Find by Exact Match

db.heroes.find({ power: "Fire Control" })

→ Only Rohan

4. Find by Number

db.heroes.find({ level: { $gt: 5 } })

→ Priya (7) and Sanya (6)

Operators You’ll Love:

OperatorMeaningExample
$gtGreater thanlevel: { $gt: 5 }
$ltLess thanlevel: { $lt: 4 }
$gteGreater or equallevel: { $gte: 6 }
$lteLess or equallevel: { $lte: 5 }
$neNot equalteam: { $ne: "Alpha" }
$inIn a listname: { $in: ["Aarav", "Priya"] }

5. Find in Arrays

db.heroes.find({ skills: "fly" })

→ Sanya (has “fly” in skills)

db.heroes.find({ skills: { $all: ["run", "jump"] } })

→ Only Aarav

6. Find in Nested Fields

db.heroes.find({ "team": "Alpha" })


Part 4: Projections: “Show Only What I Want”

By default, .find() shows all fields. Use projection to pick!

Syntax:

db.collection.find(filter, projection)

1. Show Only Name and Power


db.heroes.find(
  { isActive: true },
  { name: 1, power: 1, _id: 0 }
)

{ "name": "Aarav", "power": "Super Speed" }
{ "name": "Priya", "power": "Invisibility" }

Rules:
1 = Include this field
0 = Hide this field
Never mix 1 and 0 (except for _id)
Always hide _id with _id: 0 if not needed

2. Hide Skills


db.heroes.find(
  { team: "Alpha" },
  { skills: 0 }
)

→ Shows all except skills



Part 5: Combine Filter + Projection


db.heroes.find(
  { isActive: true, team: "Alpha" },
  { name: 1, level: 1, _id: 0 }
)

{ "name": "Aarav", "level": 5 }
{ "name": "Priya", "level": 7 }
{ "name": "Karan", "level": 3 }

Beginner Win: Like making a custom report card!



Part 6: Using Compass : Click to Query!

  1. Open Compass → heroAcademy → heroes
  2. Use Filter Bar

{ "isActive": true, "team": "Alpha" }

Compass Filter

  1. Use Projection

{ "name": 1, "level": 1, "_id": 0 }

Click & See! No typing needed.



Part 7: Advanced Filters (Pro Level)

1. Text Search (Need index!)


db.heroes.createIndex({ name: "text" })
db.heroes.find({ $text: { $search: "Priya" } })

Important: $text queries only work on fields that have a text index. Each collection can have just one text index, so make sure no other text index exists before creating a new one. You can check existing indexes with db.heroes.getIndexes().

2. Regex (Pattern Match)


db.heroes.find({ name: /^A/ })        // Starts with A
db.heroes.find({ name: /an$/i })      // Ends with "an", case-insensitive

Note: The patterns /^A/ and /an$/i are JavaScript regular expressions (regex). MongoDB supports the same regex syntax used in JavaScript, so you can easily search by text patterns like “starts with”, “ends with”, or “contains”.

3. Logical Operators


// AND (default)
db.heroes.find({ level: { $gt: 5 }, isActive: true })

// OR
db.heroes.find({
  $or: [
    { power: "Fire Control" },
    { power: "Ice Blast" }
  ]
})

// NOT
db.heroes.find({ team: { $ne: "Alpha" } })

4. Array Queries


// Has exactly 2 skills
db.heroes.find({ skills: { $size: 2 } })

// Has skill AND level > 5
db.heroes.find({
  skills: "fly",
  level: { $gt: 5 }
})

5. Dot Notation (Nested)


// If hero had address:
db.heroes.find({ "address.city": "Delhi" })


Part 8: Mini Project - Hero Search Engine!

1. Find Top Heroes (level ≥ 7)


db.heroes.find(
  { level: { $gte: 7 } },
  { name: 1, power: 1, level: 1, _id: 0 }
).pretty()

2. Find Inactive Heroes


db.heroes.find(
  { isActive: false },
  { name: 1, team: 1, _id: 0 }
)

3. Find Alpha Team Flyers


db.heroes.find(
  { team: "Alpha", skills: "fly" },
  { name: 1, _id: 0 }
)

Real-World Connection: The same query patterns you used for your Hero Academy can power real-world applications too. For example, in an e-commerce site, you might filter products by category and price, or in a school app, find students by grade and attendance. MongoDB queries make these kinds of searches fast and flexible!



Part 9: Pro Tips for All Levels

For Students & Beginners

  • Use Compass filter bar – just type!
  • Start with { field: value }
  • Always use .pretty() in mongosh

For Medium Learners


db.heroes.find()
         .sort({ level: -1 })   // High to low
         .limit(3)              // Top 3

Count matches:


db.heroes.countDocuments({ team: "Alpha" })

For Experts


db.heroes.aggregate([
  { $match: { isActive: true } },
  { $group: { _id: "$team", count: { $sum: 1 } } }
])

Index for speed:


db.heroes.createIndex({ level: 1, team: 1 })

Use explain() to debug:


db.heroes.find({ level: 5 }).explain("executionStats")


Part 10: Cheat Sheet (Print & Stick!)

Query TypeExample Code
Find alldb.heroes.find()
Filterdb.heroes.find({ level: 5 })
With operatordb.heroes.find({ level: { $gt: 5 } })
Projectiondb.heroes.find({}, { name: 1, _id: 0 })
Filter + Projectiondb.heroes.find({ team: "Alpha" }, { name: 1 })
Pretty print.pretty()
Count.countDocuments({})


Part 11: Common Mistakes & Fixes

MistakeFix
Forgetting quotesUse "power": "Fire" not power: Fire
Wrong field nameCheck with findOne()
Using == instead of :Use : in JSON: { level: 5 }
Forgetting _id: 0Add it to hide ID


Final Words

You’re a Query Master!
You just:
Used filters to find exact heroes
Used projections to show only what you want
Hunted in shell and Compass
Learned pro tricks like $or, indexing, aggregation

Your Mission:


db.heroes.find(
  { "skills": "run" },
  { name: 1, power: 1, _id: 0 }
).pretty()

Who did you find?
You’re now a Certified MongoDB Detective!



Resources:



Bonus Tip for Experts ๐Ÿง 

You can even compare values between fields within the same document using the $expr operator, a powerful feature for complex logic.


db.heroes.find({
  $expr: { $gt: ["$level", 5] }
})

This finds heroes whose level is greater than 5 without needing a fixed number in your filter!

Keep hunting treasures in your data!

Basic MongoDB Commands Tutorial: Learn mongo, mongosh, and GUI Tools Step-by-Step


Basic MongoDB Commands: mongo, mongosh, and GUI Tools

A Super Simple, Fun, and Powerful Guide for Everyone


Imagine MongoDB as a magic notebook where you can write anything—stories, drawings, lists, or even secret codes. You don’t need to follow strict rules like in a school register. This MongoDB commands tutorial teaches you how to talk to MongoDB using simple commands and cool tools.Whether you're just starting or a pro developer, this guide is made for you!

We’ll cover:

  • mongo (old shell still used sometimes)
  • mongosh (new, modern shell, the future!)
  • GUI Tools (like clicking buttons instead of typing!)

Let’s begin!


Part 1: What Are These Tools?

ToolWhat It IsBest For
mongoOld command-line shellLegacy systems, quick checks
mongoshNew and improved shell (2021+)Everyone! Modern, colorful, smart
GUI ToolsClick-and-play apps (like Compass)Beginners, visual learners, fast testing

Fun Fact: mongosh = MongoDB Shell. It’s like upgrading from a bicycle to a rocket bike!


Part 2: Starting with mongosh (The Best Way!)


Step 1: Open mongosh

After installing MongoDB (see our previous tutorial), open your terminal (Linux/macOS) or Command Prompt/PowerShell (Windows).

Type:

mongosh

You’ll see something like this:

Current Mongosh Log ID:  671a1f2c...
Connecting to:           mongodb://127.0.0.1:27017/?directConnection=true
Using MongoDB:           7.0.5
Using Mongosh:           2.2.12

test>

Beginner Tip: The > is your cursor. Type commands here and press Enter!

Basic Commands You Must Know

Let’s learn with a school example! We’ll store student info.

1. Switch to a Database

use school

Creates or switches to school database. Like opening a new notebook labeled "School".

Pro Tip: Even if it doesn’t exist, MongoDB creates it when you save data!

2. Insert a Student (Add Data)

db.students.insertOne({
  name: "Rohan",
  age: 13,
  class: "8th",
  hobbies: ["cricket", "drawing"]
})

Output:

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

Beginner Example: You just added a new student card to your magic notebook!
Expert Insight: insertOne() is atomic. Safe for one record. Use insertMany() for bulk.

3. Find Students (Search)

db.students.find()

Output:

{
  "_id": ObjectId("671a2f1d..."),
  "name": "Rohan",
  "age": 13,
  "class": "8th",
  "hobbies": ["cricket", "drawing"]
}

Pretty Print (Easier to Read):

db.students.find().pretty()

4. Find Specific Students

db.students.find({ age: 13 })
db.students.find({ "hobbies": "cricket" })

Beginner Example: Like asking, “Show me all kids who play cricket.”

Expert Tip: Use operators:
$gt → greater than
$in → in a list
$ne → not equal

db.students.find({ age: { $gt: 12 } })

5. Update a Student

db.students.updateOne(
  { name: "Rohan" },
  { $set: { class: "9th", age: 14 } }
)

Beginner Example: Rohan got promoted! We updated his class.
Expert: Use $inc to increase numbers:

db.students.updateOne(
  { name: "Rohan" },
  { $inc: { age: 1 } }
)

6. Delete a Student

db.students.deleteOne({ name: "Rohan" })

Careful! This removes the student forever.
Safer Way (for testing):

db.students.deleteMany({ class: "temp" })

7. List All Databases

show dbs

8. List Collections (Tables)

show collections

9. Drop (Delete) a Collection

db.students.drop()

10. Drop Entire Database

db.dropDatabase()

Warning: Only do this if you’re sure!


Part 3: mongo vs mongosh: What’s the Difference?

Featuremongo (Old)mongosh (New)
Release Year20112021
Syntax HighlightingNoYes (colorful!)
Auto-completeBasicSmart (Tab = magic!)
JavaScript SupportLimitedFull ES6+
Multi-line EditingHardEasy (like code editor)
Built-in Helphelp? or .help
Future-ProofDeprecatedOfficially Supported

Bottom Line: Always use mongosh!
mongo is like an old phone. It works, but why not use a smartphone?


Part 4: GUI Tools: Click Instead of Type!


1. MongoDB Compass (Free & Official)

Download: mongodb.com/compass

How to Use (Step-by-Step)

  1. Open Compass
  2. Connect to Localhost
  3. Connection String: mongodb://localhost:27017
  4. Click Connect

See Your Data Visually!
Click on school → students
You’ll see Rohan’s data in a table!
Click to Edit, Delete, or Add
No typing needed!

Beginner Win: Perfect for learning without fear of typos.
Expert Win: Export/import JSON, analyze indexes, build aggregation pipelines visually.

2. VS Code + MongoDB Extension

For Coders Who Love VS Code

  1. Install MongoDB for VS Code extension
  2. Connect to mongodb://localhost:27017
  3. Write queries in .mongodb files with syntax highlighting
// students.mongodb
use school
db.students.find({ age: { $gte: 13 } })

Run with: Ctrl + Alt + Enter
Pro Tip: Save queries, share with team, version control with Git!

3. MongoDB Atlas (Cloud) + Web Shell

No installation needed!
Go to cloud.mongodb.com
Create free cluster
Click "Open MongoSH" → Web-based mongosh

Beginner: Try MongoDB in your browser!
Expert: Deploy, scale, monitor from one dashboard.


Part 5: Mini Project: Build a "Class Diary"

Let’s practice everything!

Step 1: Create Diary

use classDiary

Step 2: Add Entries

db.entries.insertMany([
  {
    date: "2025-10-24",
    title: "Science Fair",
    mood: "excited",
    highlights: ["Won 1st prize!", "Robot worked!"]
  },
  {
    date: "2025-10-23",
    title: "Rainy Day",
    mood: "calm",
    highlights: ["Read Harry Potter", "Ate Maggi"]
  }
])

Step 3: Query Fun

// Find happy days
db.entries.find({ mood: "excited" })

// Find entries with "prize"
db.entries.find({ highlights: "Won 1st prize!" })

// Update mood
db.entries.updateOne(
  { title: "Rainy Day" },
  { $set: { mood: "cozy" } }
)

Try in Compass too! See the data as a table.


Part 6: Cheat Sheet (Print & Stick!)

CommandWhat It Does
mongoshOpen modern shell
use dbnameSwitch/create database
db.collection.insertOne({})Add one record
db.collection.find()Show all data
db.collection.find({key: value})Search
db.collection.updateOne(filter, update)Change data
db.collection.deleteOne({})Remove one record
show dbsList databases
show collectionsList tables
db.dropDatabase()Delete current DB

Part 7: Tips for All Levels


For Beginners

  • Start with Compass – no typing!
  • Use pretty() to read output easily
  • Make a "Game Scores" or "Pet Diary" project

For Medium Learners

Practice aggregation:

db.students.aggregate([
  { $match: { age: { $gte: 13 } } },
  { $group: { _id: "$class", count: { $sum: 1 } } }
])

Learn indexing:

db.students.createIndex({ name: 1 })

For Experts

Use transactions (MongoDB 4.0+):

const session = db.getMongo().startSession()
session.startTransaction()
// ... operations
session.commitTransaction()

Monitor with mongostat, mongotop
Connect via drivers (Python, Node.js)

Final Words

You now know how to talk to MongoDB like a pro!
Use mongosh for power and fun
Use Compass for visual magic
Build projects to remember forever

Your Next Step:

use myWorld
db.me.insertOne({ name: "You", skill: "MongoDB Hero", level: "Beginner → Expert" })

You did it!

Resources:

Keep exploring! The world of data is waiting for you.

๐Ÿ’ก Have questions or want me to cover MongoDB queries or Atlas setup next? Drop a comment below!

Complete Solution: Fund Transfer with Transactions

Here's the complete solution to the Practice Task on Transactions and Consistency, for both SQL and MongoDB, including full code, output, and explanations.


Complete Solution: Fund Transfer with Transactions


๐Ÿ”น Part A: SQL Solution


๐Ÿ“ 1. Table Creation

CREATE TABLE Accounts (
  AccountID INT PRIMARY KEY,
  Name VARCHAR(100),
  Balance DECIMAL(10, 2)
);

๐Ÿ“ฅ 2. Insert Sample Data

INSERT INTO Accounts (AccountID, Name, Balance) VALUES
(1, 'Aisha', 1000.00),
(2, 'Ravi', 500.00);

๐Ÿ” 3. Transaction Script

START TRANSACTION;

-- Step 1: Deduct ₹200 from Aisha
UPDATE Accounts
SET Balance = Balance - 200
WHERE AccountID = 1;

-- Step 2: Add ₹200 to Ravi
UPDATE Accounts
SET Balance = Balance + 200
WHERE AccountID = 2;

-- Final step: Commit the transaction
COMMIT;

๐Ÿ“Œ If an error occurs during either update, you would use:

ROLLBACK;

๐Ÿ“ค Expected Output (after COMMIT):

SELECT * FROM Accounts;
AccountID Name Balance
1 Aisha 800.00
2 Ravi 700.00

✅ Data is consistent and correct. Both updates were applied atomically.


๐Ÿงช Optional Test Failure Scenario

Try this (invalid ID):

START TRANSACTION;

UPDATE Accounts SET Balance = Balance - 200 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 200 WHERE AccountID = 999; -- wrong ID

ROLLBACK;

๐Ÿ” This would rollback everything. Aisha’s balance remains unchanged.


๐Ÿ”น Part B: MongoDB Solution


๐Ÿ“ฅ 1. Insert Documents

db.accounts.insertMany([
  { _id: 1, name: "Aisha", balance: 1000 },
  { _id: 2, name: "Ravi", balance: 500 }
]);

๐Ÿ” 2. MongoDB Transaction with Session

const session = db.getMongo().startSession();
session.startTransaction();

try {
  // Deduct from Aisha
  db.accounts.updateOne(
    { _id: 1 },
    { $inc: { balance: -200 } },
    { session }
  );

  // Add to Ravi
  db.accounts.updateOne(
    { _id: 2 },
    { $inc: { balance: 200 } },
    { session }
  );

  // Commit the transaction
  session.commitTransaction();
  print("✅ Transaction committed.");
} catch (error) {
  session.abortTransaction();
  print("❌ Transaction aborted:", error.message);
} finally {
  session.endSession();
}

๐Ÿ“ค Expected Output After Querying:

db.accounts.find().pretty();
[
  { _id: 1, name: "Aisha", balance: 800 },
  { _id: 2, name: "Ravi", balance: 700 }
]

✅ Like in SQL, both operations succeeded together.


๐Ÿ”ฅ Test Failure Scenario in MongoDB

Simulate a failure by modifying the second update with an invalid field:

db.accounts.updateOne(
  { _id: 999 },
  { $inc: { balance: 200 } },
  { session }
);

➡️ MongoDB will throw an error, and the first update will be rolled back automatically when abortTransaction() is called.


๐Ÿง  Final Thoughts

Operation SQL MongoDB
Begin Transaction START TRANSACTION session.startTransaction()
Commit COMMIT session.commitTransaction()
Rollback ROLLBACK session.abortTransaction()
Atomicity Built-in Requires session/replica set
Use Case High integrity systems (e.g. banks) NoSQL with transactional guarantees (MongoDB 4.0+)

Part 11: Database Security Basics

๐Ÿš€ In the next part of this tutorial series, we’ll shift focus to Database Security Basics. You'll learn about user roles, privileges, authentication, and how to protect your data from unauthorized access—an essential step for any real-world application.


๐Ÿ‘ If you found this tutorial helpful, consider following to the blog or sharing it with a friend or teammate learning databases.


๐Ÿ’ฌ Got questions or a better approach? Drop a comment below—I’d love to hear your thoughts!


๐Ÿ” Ready for more? Check out the next post on Database Security →

Featured Post

MongoDB Schema Design Patterns Explained: Embedding, Referencing & Data Modeling

Learn MongoDB schema design patterns with simple explanations and real examples. This beginner-to-expert guide covers embedding, referencin...

Popular Posts