Quiz on AI Interviews Prep Live Training Corporate Training

MongoDB Introduction.

A beginner-to-intermediate guide to MongoDB.

1. Introduction to MongoDB

MongoDB is a NoSQL document-oriented database. It stores data in flexible, JSON-like documents called BSON.

  • Schema-less
  • High performance
  • Horizontal scalability
  • Used in modern web applications

2. Installing MongoDB

Download MongoDB Community Edition from the official website.

Verify installation:

mongod --version

Start MongoDB shell:

mongosh

3. Basic Concepts

SQL MongoDB
Database Database
Table Collection
Row Document
Column Field

4. Creating Databases and Collections

// Create or switch database
use mydatabase

// Create collection
db.createCollection("users")

5. Insert Documents (Create)

// Insert one document
db.users.insertOne({
  name: "Alice",
  age: 25,
  email: "alice@example.com"
})

// Insert multiple documents
db.users.insertMany([
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 28 }
])

6. Read Documents (Find)

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

// Find with condition
db.users.find({ age: { $gt: 26 } })

// Pretty output
db.users.find().pretty()

7. Update Documents

// Update one document
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 26 } }
)

// Update multiple documents
db.users.updateMany(
  { age: { $gt: 25 } },
  { $set: { status: "active" } }
)

8. Delete Documents

// Delete one document
db.users.deleteOne({ name: "Bob" })

// Delete multiple documents
db.users.deleteMany({ age: { $lt: 25 } })

9. Indexes

Indexes improve query performance.

// Create index
db.users.createIndex({ email: 1 })

// View indexes
db.users.getIndexes()

10. Aggregation Framework

db.users.aggregate([
  { $match: { age: { $gt: 25 } } },
  { $group: { _id: "$status", total: { $sum: 1 } } }
])

11. Relationships in MongoDB

Embedding

{
  name: "Order1",
  items: [
    { product: "Pen", qty: 2 },
    { product: "Book", qty: 1 }
  ]
}

Referencing

{
  orderId: 1,
  userId: ObjectId("64ad1234...")
}

12. Best Practices

  • Design schema based on queries
  • Use indexes wisely
  • Avoid large documents
  • Use aggregation for analytics
  • Backup regularly