~/VibeHandbook
$39

Databases

mongodb.com

MongoDB

What it is

MongoDB is a document database that stores data as flexible, JSON-like documents (BSON) grouped into collections. Instead of rigid tables and rows, each document can have its own shape, which makes it easy to evolve a model quickly. It is a popular choice for applications whose data maps naturally to nested objects.

Strengths

  • Flexible schema: documents can vary and evolve without migrations.
  • Data maps directly to application objects, reducing translation code.
  • Rich query language plus a powerful aggregation pipeline.
  • Horizontal scaling through built-in sharding.
  • Strong support for nested and array fields.

Trade-offs

  • Easy to create inconsistent data without disciplined schema design.
  • Multi-document transactions exist but are heavier than in relational stores.
  • Joins ($lookup) are limited compared to SQL; data is often denormalized.
  • Denormalization can duplicate data and complicate updates.

When to use it

Choose MongoDB for content management, catalogs, user profiles, event logging, and apps with evolving or hierarchical data where documents fit better than normalized tables.

Vibe coding fit

When directing AI, do not let "schemaless" mean "no plan." Ask the AI to define a clear document shape and enforce it with JSON Schema validation or an ODM like Mongoose, including required fields and types. Tell it whether to embed related data or reference it by id based on access patterns, and to add indexes for the fields you query and sort on. A good tip: have the AI use parameterized query objects (never build queries from raw user strings) and explain its embed-versus-reference choice so you understand the read/write and update costs.

// Schema validation keeps documents consistent
db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["email", "createdAt"],
      properties: {
        email:     { bsonType: "string" },
        createdAt: { bsonType: "date" },
        roles:     { bsonType: "array", items: { bsonType: "string" } }
      }
    }
  }
});

db.users.createIndex({ email: 1 }, { unique: true });

// Aggregation: count active users per role
db.users.aggregate([
  { $match: { active: true } },
  { $unwind: "$roles" },
  { $group: { _id: "$roles", count: { $sum: 1 } } }
]);