MongoDB Guide

Database & Collection Creation, Document Operations & Queries

This lesson covers step-by-step instructions on how to create a MongoDB database, collections, and perform CRUD operations using mongosh.

1. Install and Start MongoDB

Ensure MongoDB is installed and running:

mongod --dbpath="C:\data\db"  # Windows
sudo systemctl start mongod    # Linux/macOS

Then, start the MongoDB shell at comand terminal or VSCode terminal via extension:

mongosh # at cmd 
Launch MongoDB Shell # at vsc 

2. Create a Database

MongoDB does not require explicit database creation. It automatically creates one when you insert a document.

Switch or Create a Database

use myDatabase

āœ”ļø If myDatabase does not exist, MongoDB will create it when you insert data.


3. Create a Collection

MongoDB collections are like tables in SQL. You can create them explicitly or let MongoDB create them automatically.

Explicit Collection Creation

db.createCollection("users")

āœ”ļø This creates an empty users collection.

Implicit Collection Creation

MongoDB automatically creates a collection when inserting a document:

db.users.insertOne({ name: "Alice", age: 30 })

4. Insert Documents

MongoDB stores data as documents in BSON format (similar to JSON).

Insert a Single Document

db.users.insertOne({ name: "Alice", age: 30, city: "New York" })

Insert Multiple Documents

db.users.insertMany([
  { name: "Bob", age: 25, city: "Los Angeles" },
  { name: "Charlie", age: 35, city: "Chicago" }
])

āœ”ļø The _id field is automatically generated for each document.


5. Find (Retrieve) Documents

Find All Documents

db.users.find()

Pretty Print Results

db.users.find().pretty()

Find One Document

db.users.findOne({ name: "Alice" })

6. Update Documents

Update a Single Document

db.users.updateOne(
  { name: "Alice" }, 
  { $set: { age: 31, city: "San Francisco" } }
)

Update Multiple Documents

db.users.updateMany(
  { city: "Los Angeles" }, 
  { $set: { city: "San Diego" } }
)

7. Delete Documents

Delete One Document

db.users.deleteOne({ name: "Charlie" })

Delete Multiple Documents

db.users.deleteMany({ age: { $gt: 30 } })  # Deletes all users older than 30

8. Sorting & Limiting Results

Sort in Ascending Order (1)

db.users.find().sort({ age: 1 })

Sort in Descending Order (-1)

db.users.find().sort({ age: -1 })

Limit the Number of Results

db.users.find().limit(2)

9. Comparison Operators

MongoDB has SQL-like comparison operators:

Operator
Description
Example

$eq

Equal to

{ age: { $eq: 30 } }

$ne

Not equal to

{ age: { $ne: 25 } }

$gt

Greater than

{ age: { $gt: 30 } }

$lt

Less than

{ age: { $lt: 30 } }

$gte

Greater than or equal to

{ age: { $gte: 25 } }

$lte

Less than or equal to

{ age: { $lte: 40 } }

āœ”ļø Example: Find users older than 30

db.users.find({ age: { $gt: 30 } })

10. Logical Operators

MongoDB also supports logical operators:

Operator
Description
Example

$and

Match all conditions

{ $and: [{ age: { $gt: 25 } }, { city: "San Diego" }] }

$or

Match any condition

{ $or: [{ age: 25 }, { city: "New York" }] }

$not

Negate a condition

{ age: { $not: { $gt: 30 } } }

āœ”ļø Example: Find users older than 25 AND in "San Diego":

db.users.find({ $and: [{ age: { $gt: 25 } }, { city: "San Diego" }] })

11. Indexes for Performance

Indexes speed up queries by reducing the need for full collection scans.

Create an Index on a Field

db.users.createIndex({ name: 1 })  # Ascending index on "name"

View Existing Indexes

db.users.getIndexes()

Delete an Index

db.users.dropIndex("name_1")

12. Drop a Collection or Database

Drop a "users" Collection

db.users.drop()

Drop an Entire Database

db.dropDatabase()

Example Document & Data Types

//Json or Bson Data Type
{
  "_id": ObjectId("65af67cdef12345"),
  "name": "Alice",
  "age": 30,
  "city": "New York",
  "email": "[email protected]",
  "isVerified": true,
  "score": 95.5,
  "hobbies": ["reading", "traveling"],
  "createdAt": ISODate("2024-01-25T10:00:00Z")
}
Data Type
Example

String

"name": "Alice"

Number

"age": 30

Boolean

"isVerified": true

Array

"hobbies": ["reading", "traveling"]

Object

"address": { "city": "New York", "zip": "10001" }

Date

"createdAt": ISODate("2024-01-25T10:00:00Z")

ObjectId

"_id": ObjectId("65af67cdef12345")


Conclusion

This guide provides an overview of how to: āœ… Create databases and collections āœ… Insert, update, delete, and query documents āœ… Use sorting, limiting, comparison, and logical operators āœ… Optimize queries with indexes

šŸš€ Now, you can start working efficiently with MongoDB using mongosh!

Last updated