Lesson 3 of 18

Databases & Collections

Creating Databases and Collections

MongoDB creates databases and collections automatically when you first insert data. You can also create them explicitly.

Example
// Switch to a database (creates if doesn't exist)
use shopDB

// Create collection explicitly
db.createCollection("products")

// Or just insert — collection is created automatically
db.products.insertOne({ name: "Laptop", price: 999 })

// List collections
show collections

// Drop a collection
db.products.drop()

// Drop entire database
db.dropDatabase()

Collection Options

Collections can have options like capped size, validation rules, and more.

Example
// Capped collection (fixed size, FIFO)
db.createCollection("logs", {
  capped: true,
  size: 1048576,  // 1MB max
  max: 1000       // 1000 docs max
})

// Collection with validation
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      required: ["name", "email"],
      properties: {
        name: { bsonType: "string" },
        email: { bsonType: "string" },
        age: { bsonType: "int", minimum: 0 }
      }
    }
  }
})