MongoDB Collections

Working with Collections

A collection is a grouping of MongoDB documents. It is the equivalent of an RDBMS table. Collections live inside a specific database.

Automatic Creation

Just like databases, collections are created lazily. When you insert a document, the collection is made. You rarely need to create one manually.

Explicit Creation

Sometimes manual creation is required. You might want to set specific collection rules. You use db.createCollection() for this.

Capped Collections

A capped collection has a fixed size. Once it is full, older documents are overwritten. They are perfect for storing high-volume logs.

Schema Validation

Collections are schemaless by default. However, you can attach validation rules. This prevents bad data from entering your app.

Listing Collections

You can see collections in your database easily. Run the show collections command in the shell. It will list every collection instantly.

Collection Examples:

// 1. Automatic creation via insert
db.users.insertOne({ name: "Alice" });

// 2. Explicit creation with options db.createCollection("logs", { capped: true, size: 100000 });

Renaming Collections

You can rename collections if needed. Use the renameCollection() method. This changes the name without moving data.

Dropping Collections

Dropping a collection deletes it entirely. Use db.collectionName.drop(). This removes all documents and associated indexes.

Best Practices

Use plural, lowercase names for collections. For example, use users instead of User. Keep collection structures logically related.

Summary

Collections organize your JSON documents. They are highly flexible and adaptable.

Exercise

What type of collection automatically overwrites its oldest entries when full?