MongoDB Create Collection
MongoDB automatically creates a collection when you insert the first document. However, you can manually create collections with specific options like validation rules or storage engine settings. This guide explains how to create a collection using MongoDB Shell, Node.js (Mongoose), and Compass.
1. Create a Collection Automatically
MongoDB creates a collection automatically when you insert a document if the collection does not exist.
Example: Insert a Document to Create a Collection
- If
myCollection
does not exist inmyDatabase
, MongoDB creates it automatically. - The document
{ name: "John Doe", age: 30, city: "New York" }
is inserted.
2. Create a Collection Explicitly
You can explicitly create a collection using the createCollection()
method.
Syntax:
Example: Create a Simple Collection
- Creates a collection named
users
inmyDatabase
.
3. Create a Collection with Options
You can specify options like capped collection, size limit, and max documents.
Example: Create a Capped Collection (Fixed Size)
capped: true
→ Limits the collection’s size.size: 100000
→ Maximum storage in bytes.max: 500
→ Maximum number of documents.
Example: Create a Collection with a Validation Schema
- Ensures that every document in
employees
hasname
(string) andage
(integer).
4. List All Collections
To check the collections in a database:
or
5. Drop (Delete) a Collection
To remove a collection from the database:
- Deletes
myCollection
from the current database.
Summary
Method | Description |
---|---|
db.createCollection("name") | Creates an empty collection |
db.createCollection("name", options) | Creates a collection with options |
show collections | Lists all collections in the database |
db.collectionName.drop() | Deletes a collection |
Would you like help with specific use cases? 🚀