~/VibeHandbook
$39

Databases

mongodb.com

MongoDB

What it is

Think of a folder of index cards where each card can carry different fields, instead of a fixed spreadsheet where every row must have the same columns. MongoDB works like the folder of cards. It is a document that stores data as flexible documents (think of each "document" as one card) grouped into collections. The documents are saved in a format called BSON, which is MongoDB's binary form of (JavaScript Object Notation), a common way to write data as named fields. 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 (Structured Query Language); data is often denormalized.
  • Denormalization (storing copies of the same data in more than one place to avoid lookups) 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 (Object-Document Mapper) 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, which means never building queries by gluing raw user text together. Also ask it to explain its embed-versus-reference choice. That way 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 } } }
]);