CodeToLive

MongoDB Schema Design

Design effective MongoDB schemas based on your application's data access patterns.

Embedding Documents (One-to-One)

// User with embedded address
{
  _id: "user123",
  name: "Alice",
  address: {
    street: "123 Main St",
    city: "New York",
    zip: "10001"
  }
}

Best when data is always accessed together.

Embedding Arrays (One-to-Many)

// Blog post with embedded comments
{
  _id: "post1",
  title: "MongoDB Schema Design",
  comments: [
    { user: "Bob", text: "Great post!" },
    { user: "Charlie", text: "Very helpful" }
  ]
}

Good for limited number of related items.

Referencing Documents (Many-to-Many)

// Books and Authors (separate collections)
// books collection
{
  _id: "book1",
  title: "MongoDB Guide",
  author_ids: ["auth1", "auth2"]
}

// authors collection
{
  _id: "auth1",
  name: "John Doe"
}

Better for large or unbounded relationships.

Hybrid Approach

// Product with some embedded and some referenced data
{
  _id: "prod1",
  name: "Laptop",
  price: 999,
  specs: { // Embedded
    cpu: "i7",
    ram: "16GB"
  },
  reviews: [ // References
    { review_id: "rev1", rating: 5 },
    { review_id: "rev2", rating: 4 }
  ]
}

Schema Validation

// Create collection with validation rules
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name: { bsonType: "string" },
        email: { 
          bsonType: "string",
          pattern: "^.+@.+\\..+$"
        },
        age: { 
          bsonType: "int",
          minimum: 0 
        }
      }
    }
  }
})
← Back to Tutorials