Skip to content

MongoDB Create Collection

Collections are containers for documents in MongoDB, similar to tables in relational databases but without requiring a predefined schema.

Creating Collections

Collections are created automatically when inserting documents:

javascript
use mydb

// Automatically creates users collection and inserts document
db.users.insertOne({ name: "John", age: 25 })

// View collection list
show collections

Method 2: Explicit Creation

Use the createCollection() method:

javascript
db.createCollection("users")

Method 3: Creation with Options

javascript
db.createCollection("logs", {
  capped: true,           // Capped collection
  size: 5242880,          // Maximum size 5MB
  max: 5000               // Maximum document count
})

Collection Options

Common Options

OptionTypeDescription
cappedbooleanWhether it's a capped collection
sizenumberMaximum size for capped collection (bytes)
maxnumberMaximum document count for capped collection
validatorobjectDocument validation rules
validationLevelstringValidation level
validationActionstringAction on validation failure

Creating Collection with Validation

javascript
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name: {
          bsonType: "string",
          description: "Name is required"
        },
        email: {
          bsonType: "string",
          pattern: "^.+@.+$",
          description: "Invalid email format"
        },
        age: {
          bsonType: "int",
          minimum: 0,
          maximum: 150
        }
      }
    }
  },
  validationLevel: "strict",    // strict | moderate
  validationAction: "error"     // error | warn
})

Collection Naming Rules

Naming Conventions

  • Cannot be empty string
  • Cannot contain \0 (null character)
  • Cannot start with system. (system reserved)
  • Cannot contain $ character
  • Recommended: lowercase letters with underscores

Valid Names

javascript
db.createCollection("users")           // ✓
db.createCollection("user_profiles")   // ✓
db.createCollection("orders_2024")     // ✓

Invalid Names

javascript
db.createCollection("")                // ✗ Empty string
db.createCollection("system.users")    // ✗ System reserved
db.createCollection("my$collection")   // ✗ Contains $

Viewing Collections

List All Collections

javascript
show collections

// Or
show tables

// Or
db.getCollectionNames()

Get Collection Statistics

javascript
db.users.stats()

Check if Collection Exists

javascript
// Method 1
db.getCollectionNames().indexOf("users") >= 0

// Method 2
db.users.exists() !== null

Capped Collections

Characteristics

  • Fixed size, circular overwrite when full
  • Automatically maintains insertion order
  • Suitable for logs, caches, etc.

Creating Capped Collection

javascript
db.createCollection("system_logs", {
  capped: true,
  size: 104857600,    // 100MB
  max: 10000          // Maximum 10000 documents
})

Querying Capped Collections

javascript
// Query by insertion order
db.system_logs.find().sort({ $natural: 1 })   // Ascending
db.system_logs.find().sort({ $natural: -1 })  // Descending

Converting Regular to Capped Collection

bash
# Need to dump and restore
mongodump --db mydb --collection logs
mongorestore --db mydb --collection logs_new

# In mongosh
db.logs.renameCollection("logs_backup")
db.createCollection("logs", { capped: true, size: 10000000 })

Collection Operation Examples

Complete Example

javascript
use ecommerce

// 1. Create users collection
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["username", "email"],
      properties: {
        username: { bsonType: "string" },
        email: { bsonType: "string" },
        created_at: { bsonType: "date" }
      }
    }
  }
})

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

// 3. Create orders collection
db.createCollection("orders")

// 4. Create capped logs collection
db.createCollection("app_logs", {
  capped: true,
  size: 52428800,  // 50MB
  max: 50000
})

// 5. View all collections
show collections

Modifying Collections

Modify Validation Rules

javascript
db.runCommand({
  collMod: "users",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email", "age"],
      properties: {
        name: { bsonType: "string" },
        email: { bsonType: "string" },
        age: { bsonType: "int", minimum: 18 }
      }
    }
  },
  validationLevel: "moderate"
})

Collection Information

Get Collection Details

javascript
// Collection statistics
db.users.stats()

// Collection options
db.getCollectionInfos({ name: "users" })

// Validation rules
db.getCollectionInfos({ name: "users" })[0].options.validator

Best Practices

1. Naming Conventions

javascript
// Recommended
db.user_profiles
db.order_items
db.system_logs

// Not recommended
db.UserProfiles    // Mixed case
db.order-items     // Hyphens
db.data            // Too generic

2. Collection Design

javascript
// Related data in same collection
db.users        // User basic info
db.user_profiles // User detailed info (one-to-one)

// Or embed
db.users = {
  basic_info: {...},
  profile: {...}
}

3. Use Validation

javascript
// Production environments should enable validation
db.createCollection("payments", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["amount", "currency", "status"],
      properties: {
        amount: { bsonType: "decimal" },
        currency: { enum: ["USD", "EUR", "GBP"] },
        status: { enum: ["pending", "completed", "failed"] }
      }
    }
  }
})

Summary

Key points for creating collections:

  • Usually use implicit creation (auto-created when inserting documents)
  • Capped collections are suitable for log-like data
  • Can use validation rules to ensure data quality
  • Follow naming conventions for maintainability

In the next chapter, we will learn about MongoDB Drop Collection.

Content is for learning and research only.