A collection is a grouping of MongoDB documents. It is the equivalent of an RDBMS table. Collections live inside a specific database.
Just like databases, collections are created lazily. When you insert a document, the collection is made. You rarely need to create one manually.
Sometimes manual creation is required. You might want to set specific collection rules. You use db.createCollection() for this.
A capped collection has a fixed size. Once it is full, older documents are overwritten. They are perfect for storing high-volume logs.
Collections are schemaless by default. However, you can attach validation rules. This prevents bad data from entering your app.
You can see collections in your database easily. Run the show collections command in the shell. It will list every collection instantly.
// 1. Automatic creation via insert
db.users.insertOne({ name: "Alice" });
// 2. Explicit creation with options
db.createCollection("logs", {
capped: true,
size: 100000
});
You can rename collections if needed. Use the renameCollection() method. This changes the name without moving data.
Dropping a collection deletes it entirely. Use db.collectionName.drop(). This removes all documents and associated indexes.
Use plural, lowercase names for collections. For example, use users instead of User. Keep collection structures logically related.
Collections organize your JSON documents. They are highly flexible and adaptable.
What type of collection automatically overwrites its oldest entries when full?