Creating Collections in MongoDB: A Comprehensive Guide
Creating Collections in MongoDB: A Comprehensive Guide
Creating a collection in MongoDB is essential for storing documents. A collection can be likened to a table in relational databases, where multiple documents (or records) can be stored.
Key Concepts
- What is a Collection?
- A collection is a grouping of MongoDB documents.
- Collections are schema-less, which means that documents within a collection can have different fields.
- Creating a Collection
- You can create a collection explicitly or allow MongoDB to create one implicitly when you first insert a document.
Methods to Create a Collection
- Using the
createCollection()
Method- Syntax:
- Example:
- Inserting a Document
- You can also create a collection by inserting a document into a non-existent collection.
- Example:
- In this instance, the
users
collection is created automatically.
db.users.insertOne({ name: "Alice", age: 30 })
db.createCollection("users")
db.createCollection("collectionName", options)
Options for createCollection()
capped
: Creates a capped collection (fixed size).size
: Specifies the maximum size of the capped collection.maxDocuments
: Limits the number of documents in the capped collection.
Example of a Capped Collection
db.createCollection("logs", { capped: true, size: 10000, maxDocuments: 500 })
Conclusion
Creating collections in MongoDB is straightforward and can be accomplished either explicitly or implicitly through document insertion. Understanding how to work with collections is fundamental for effective database management in MongoDB.