0Pricing
MongoDB Academy · Aula

Coleções versus tabelas SQL

Compare as coleções do MongoDB com tabelas relacionais e entenda como um esquema flexível altera o design dos dados.

Coleções versus tabelas SQL é uma aula grátis de MongoDB Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de MongoDB Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de MongoDB Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Tables vs Collections at a Glance

SQL's basic unit is the table, where every row has identical columns. MongoDB's is the collection — a group of documents that can each differ.

Fixed Schema: The SQL Way

SQL needs a fixed schema defined before any data goes in, and changing it later can rebuild the whole table. Rigid, but predictable and storage-efficient.

-- SQL table: schema defined upfront, rigid
CREATE TABLE users (
  id         SERIAL PRIMARY KEY,
  name       VARCHAR(100) NOT NULL,
  email      VARCHAR(200) UNIQUE NOT NULL,
  age        INT,
  created_at TIMESTAMP DEFAULT NOW()
);
-- Every row must have exactly these columns

Flexible Schema: The MongoDB Way

A MongoDB collection appears the moment you insert — no schema needed. This flexible schema is great for prototyping, but your code must handle missing fields.

// No schema definition needed - collection created on first insert
db.users.insertOne({ name: 'Alice', email: 'alice@test.com', age: 30 });

// Next insert can have completely different fields
db.users.insertOne({ name: 'Bob', email: 'bob@test.com', company: 'Acme', role: 'admin' });

// Both documents live in the same 'users' collection

Schema vs Schema-Less: The Trade-Off

Neither wins outright. Fixed schemas guard against bad data; flexible ones let you move fast. MongoDB's JSON Schema validation gives you optional middle ground.

Normalization vs Denormalization

SQL favors normalization — splitting data across tables. MongoDB favors denormalization — embedding related data together, so you read it all in one go without JOINs.

// SQL normalized: address in separate table
// SELECT u.name, a.city FROM users u JOIN addresses a ON a.user_id = u.id

// MongoDB denormalized: address embedded in user document
{
  _id: ObjectId('...'),
  name: 'Alice',
  address: { city: 'London', zip: 'EC1A' }   // no JOIN needed
}

Creating Collections Explicitly

Collections appear automatically, but createCollection lets you set options up front — like a capped collection for logs or a validator. The code shows one.

// Create a capped collection explicitly
db.createCollection('appLogs', {
  capped: true,
  size: 10485760,   // 10 MB maximum size
  max: 50000        // optional: max 50,000 documents
});
// When full, oldest documents are automatically removed

Listing and Dropping Collections

A few handy commands list, count, and drop collections. To empty one without deleting it, use deleteMany — there's no TRUNCATE in MongoDB. The code shows them.

// Useful collection management commands in mongosh
db.getCollectionNames();
// ['users', 'orders', 'products']

db.users.countDocuments({});
// 4823

db.users.stats().storageSize;
// 2097152 (bytes)

// Delete all documents but keep the collection:
db.users.deleteMany({});
// { acknowledged: true, deletedCount: 4823 }

The _id Field and Primary Keys

Every collection has _id as its primary key, with an automatic unique index. You can supply your own _id — like a product SKU — as long as it's unique.

// Custom _id values
db.products.insertOne({
  _id: 'SKU-HEADPHONES-BLK-42',   // string _id
  name: 'Wireless Headphones Black',
  price: 79.99
});

// Lookup by custom _id is O(log n) via the _id index
db.products.findOne({ _id: 'SKU-HEADPHONES-BLK-42' });

Index Structure Differences

Both SQL and MongoDB use B-tree indexes, but MongoDB can index nested fields and array elements too. So flexible schemas don't cost you query speed.

// Index a nested field and an array field
db.users.createIndex({ 'address.city': 1 });
// Now queries on city use an index:
db.users.find({ 'address.city': 'Chicago' });

// Multikey index on array field - indexes each element
db.products.createIndex({ tags: 1 });
db.products.find({ tags: 'electronics' }); // uses multikey index

Transactions: Tables vs Collections

Since v4.0, MongoDB supports multi-document transactions. But by embedding related data in one document, you often get atomic updates without needing them at all.

// Single-document atomicity (always available)
// Updating order status and adding a tracking number
db.orders.updateOne(
  { _id: orderId },
  { $set: { status: 'shipped', trackingNumber: 'UPS123456' } }
);
// These two field updates happen atomically - no transaction needed

When to Choose Tables Over Collections

Sometimes SQL tables are the better pick: stable schemas, heavy JOINs, or strict foreign-key integrity. Choose the right tool, not the trendiest one.

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

You learned collections don't force a schema, MongoDB embeds related data to skip JOINs, and every collection auto-indexes _id. Next: databases and namespaces.

Perguntas Frequentes

A aula “Coleções versus tabelas SQL” é grátis?

Sim — o texto completo de “Coleções versus tabelas SQL” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de MongoDB Academy, atualize para CoddyKit PRO. O curso de MongoDB Academy inclui 4 aulas no total.

O que vou aprender em “Coleções versus tabelas SQL”?

Compare as coleções do MongoDB com tabelas relacionais e entenda como um esquema flexível altera o design dos dados. Você pratica MongoDB Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar MongoDB Academy?

Nenhuma experiência prévia é necessária. MongoDB Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Coleções versus tabelas SQL”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de MongoDB Academy?

Sim. Cada aula de MongoDB Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. O que é um documento BSON?
  2. Coleções versus tabelas SQL
  3. Bancos de dados, coleções e espaços de nomes
  4. Fundamentos do shell mongosh
← Voltar para MongoDB Academy