Showing posts with label mongosh. Show all posts
Showing posts with label mongosh. Show all posts

Creating Your First MongoDB Database and Collection (Step-by-Step Tutorial)



Creating Your First MongoDB Database and Collection

A Super Fun, Step-by-Step Adventure for Beginner to Expert Level


What is MongoDB?
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents instead of rigid tables used in SQL databases. This makes it perfect for modern apps, projects, and learning how data really works!

Imagine you’re opening a magic toy box where you can store toys, games, books, and secret treasures — all in one place! In MongoDB, a database is your toy box, and a collection is a shelf inside it. This tutorial teaches you how to create your first database and collection using simple words, fun examples, and real tools, perfect for students, but packed with pro tips for experienced learners.

We’ll use:

  • mongosh (the modern MongoDB shell)
  • MongoDB Compass (a click-and-play GUI)
  • Real images from MongoDB
  • A fun "Pet Shop" project

Level: Beginners to Pro


Let’s open the toy box!

Part 1: What Are Databases and Collections?

TermReal-Life ExampleMongoDB Meaning
DatabaseA big toy boxA container for all your data
CollectionA shelf inside the toy boxA group of similar items (documents)

Fun Fact: You don’t need to “create” a database first! MongoDB makes it automatically when you add data!


Part 2: Method 1- Using mongosh (The Command Way)

Step 1: Open mongosh

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

Type:

mongosh

You’ll see:

test>

Beginner Tip: The > is your magic wand. Type spells (commands) here!

Step 2: Create Your First Database – petshop

use petshop

What happens?
MongoDB switches to (or creates) a database called petshop.
But it’s invisible until you add data!
Like: Opening a new toy box labeled “Pet Shop” , but it’s empty!

Step 3: Create Your First Collection – animals

db.animals.insertOne({
  name: "Buddy",
  species: "Dog",
  age: 3,
  color: "Golden",
  loves: ["balls", "walks", "treats"]
})

Output:

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

Magic Moment!
petshop database is now created
animals collection is now created
Buddy the dog is now stored
Beginner Example: You just put the first toy (Buddy) on the “Animals” shelf!

Step 4: Add More Pets!

db.animals.insertMany([
  {
    name: "Whiskers",
    species: "Cat",
    age: 2,
    color: "Gray",
    loves: ["napping", "laser pointer"]
  },
  {
    name: "Goldie",
    species: "Fish",
    age: 1,
    color: "Orange",
    loves: ["swimming", "bubbles"]
  }
])

Pro Tip: Use insertMany() for bulk add faster and cleaner!

Step 5: See Your Data!

db.animals.find()

Output:

{ "_id": ObjectId("..."), "name": "Buddy", ... }
{ "_id": ObjectId("..."), "name": "Whiskers", ... }
{ "_id": ObjectId("..."), "name": "Goldie", ... }

Pretty View:

db.animals.find().pretty()

Beginner Win: You just opened the toy box and saw all pets!

Step 6: Check What’s Created

show dbs

→ Shows all databases (now includes petshop)

show collections

→ Shows animals

db.animals.countDocuments()

→ Returns 3 (total pets)



Part 3: Method 2 – Using MongoDB Compass (The Click Way)

Step 1: Open Compass

Download: mongodb.com/compass
Open the app.

Step 2: Connect to Your Local MongoDB

Connection: mongodb://localhost:27017
Click Connect

Step 3: Create Database & Collection Visually

Click "Create Database"
Name: petshop
Collection: animals
Click Create

Step 4: Add a Pet with Clicks!

Click on animals collection
Click "Add Data" → "Insert Document"
Paste or type:

{
  "name": "Fluffy",
  "species": "Rabbit",
  "age": 1,
  "color": "White",
  "loves": ["carrots", "hopping"]
}

Click Insert
Beginner Magic: No typing commands! Just click and add!

Step 5: See Your Pet Shop!

You’ll see all pets in a beautiful table:
Expert Feature: Click column headers to sort, or use filter bar:

{ "species": "Dog" }


Part 4: Understanding the Magic Behind the Scenes

ActionWhat MongoDB Does Automatically
use petshopSwitches context (no file created yet)
insertOne()Creates DB + Collection + Document
show dbsLists only DBs with data
No CREATE DATABASE command needed!


Part 5: Mini Project – Build a Full Pet Shop!

1. Add More Collections

// Toys collection
db.toys.insertOne({
  name: "Squeaky Ball",
  for: "Dog",
  price: 5.99,
  inStock: true
})

// Owners collection
db.owners.insertOne({
  name: "Aarav",
  phone: "9876543210",
  pets: ["Buddy", "Whiskers"]
})

2. Smart Queries

// Find dogs older than 2
db.animals.find({ species: "Dog", age: { $gt: 2 } })

// Find pets that love "treats"
db.animals.find({ loves: "treats" })

// Count cats
db.animals.countDocuments({ species: "Cat" })

3. Update a Pet

db.animals.updateOne(
  { name: "Buddy" },
  { $set: { age: 4, vaccinated: true } }
)

4. Delete a Toy (Carefully!)

db.toys.deleteOne({ name: "Squeaky Ball" })


Part 6: Pro Tips for All Levels

For students & Beginners

  • Use Compass to avoid typos
  • Make a "Game Collection" with characters
  • Always use .pretty() in mongosh

For Medium Learners

db.animals.createIndex({ species: 1 })
db.createCollection("animals", {
  validator: {
    $jsonSchema: {
      required: ["name", "species"],
      properties: {
        age: { bsonType: "int", minimum: 0 }
      }
    }
  }
})

Note: In modern versions of MongoDB, "bsonType": "int" can also be written as "bsonType": "number" depending on your environment and data type. Both work correctly as long as the field value matches the expected numeric format.


For Experts

db.createCollection("logs", { capped: true, size: 100000 })

db.animals.createIndex({ name: "text" })
db.animals.find({ $text: { $search: "Buddy" } })

// Use Atlas for cloud (no install!)
cloud.mongodb.com


Part 7: Cheat Sheet (Print & Stick!)

CommandWhat It Does
mongoshOpen shell
use dbnameSwitch/create database
db.collection.insertOne({})Add one item
db.collection.insertMany([])Add many items
db.collection.find()Show all
db.collection.find().pretty()Show nicely
show dbsList databases
show collectionsList shelves
db.collection.drop()Delete shelf
db.dropDatabase()Delete entire toy box


Part 8: Common Mistakes & Fixes

MistakeFix
Typing create database petshopNot needed! Just use petshop
Forgetting quotes in stringsUse "name": "Buddy"
Using wrong collection nameCheck with show collections
Data not showing in show dbsYou must insert data first!


💡 Quick Quiz & Challenge

  1. What command automatically creates both a database and collection in MongoDB?
  2. How do you display all documents in a collection neatly?
  3. Which MongoDB GUI lets you create databases with just clicks?

Bonus Challenge:
Try adding an owners-to-pets relationship using ObjectId references. Here’s an example to get you started:

// Step 1: Insert pets
db.animals.insertOne({
  name: "Buddy",
  species: "Dog"
})

// Step 2: Get Buddy's _id
var buddyId = db.animals.findOne({ name: "Buddy" })._id

// Step 3: Create an owner referencing Buddy
db.owners.insertOne({
  name: "Aarav",
  pets: [buddyId]
})

// Step 4: Verify relationship
db.owners.aggregate([
  {
    $lookup: {
      from: "animals",
      localField: "pets",
      foreignField: "_id",
      as: "petDetails"
    }
  }
])

🎉 Pro Tip: This approach helps you model real relationships between collections just like linking tables in SQL, but more flexible!



Final Words

You Did It!


You just:
  • Created your first database (petshop)
  • Made a collection (animals)
  • Added, viewed, and managed real data
  • Used both command line and GUI

Fun Learned: Infinite

Your Next Mission:

use myWorld
db.heroes.insertOne({
  name: "You",
  power: "MongoDB Master",
  level: "Expert"
})

You’re now a Certified MongoDB Creator!



👉 Next Tutorial: Level Up Your MongoDB Skills

Now that you’ve mastered databases and collections, take your next step in learning MongoDB queries and relationships!

🚀 Next: Master MongoDB Queries and Relationships

Coming soon: Learn how to search, filter, and connect data across collections like a pro!

Resources:

Keep building magic toy boxes! 🧸✨

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!

Featured Post

Master MongoDB with Node.js Using Mongoose: Complete Guide

Working with MongoDB from Node.js using Mongoose Your Magical Mongoose Pet That Makes MongoDB Super Easy For Beginner to Expert Level ...

Popular Posts