MongoDB Create Collection
MongoDB Create Collection
The MongoDB create collection
operation is used to create a new collection within a database. Collections in MongoDB are analogous to tables in relational databases and are used to store documents.
Syntax
db.createCollection(name, options)
The db.createCollection()
method has the following parameters:
name
: The name of the collection to create.options
: Optional. A document that specifies the options for the collection (e.g., capped, size, max).
Example MongoDB Create Collection
Let's look at some examples of how to create a collection in MongoDB:
1. Basic Create Collection
db.createCollection("programGuru")
This command creates a new collection named programGuru
in the current database.
2. Create a Capped Collection
db.createCollection("log", { capped: true, size: 5242880, max: 5000 })
This command creates a new capped collection named log
with a maximum size of 5 MB and a maximum of 5000 documents.
Full Example
Let's go through a complete example that includes switching to a database, creating a collection, and verifying its creation.
Step 1: Switch to a Database
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
Step 2: Create a Collection
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
Step 3: Verify the Collection Creation
This step involves listing the collections in the myDatabase
database to verify that programGuru
has been created.
show collections
This command lists all collections in the current database. You should see programGuru
in the list.
Conclusion
The MongoDB create collection
operation is a fundamental task for structuring your database. By understanding how to create collections, you can effectively organize and manage your data in MongoDB.