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.
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).Let's look at some examples of how to create a collection in MongoDB:
db.createCollection("programGuru")
This command creates a new collection named programGuru
in the current database.
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.
Let's go through a complete example that includes switching to a database, creating a collection, and verifying its creation.
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
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.
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.