What is the MongoDB Collection?
MongoDB collection is a group of documents. It is similar to the table in a relational database management system. A collection can be present in a single database and it can have different fields.
MongoDB Create Collection
To create a collection in MongoDB we can use the createCollection() Method.
The createCollection() Method
The createCollection(name, options) Method is used to create a collection in MongoDB. The name indicates the name of the collection and the options indicates the different type of collection configuration parameters such as capped which is used for the Capped collection that is a fixed size of the collection, size which is used to specify the size of Capped collection, max that is used to define the maximum number of size for the Capped collection, autoIndexId that is used to automatically creates an index on _id fields.
Command:
We will create a collection with the name "testcollection" under "mongodb_test" database.
> use mongodb_test> db.createcollection("testcollection")
> show collections
Output:
Once the collection is created we can see the collection detail with the show collections command as mentioned in the below screenshot.
In MongoDB, collections are automatically created when we insert some document into the database. For example, if we run the below command to insert the document the collection will be created automatically.
Command:
> db.course.insert({"course_name":"cloudduggu mongodb tutorial"})> show collections
Output:
MongoDB Drop Collection
To drop a collection in MongoDB, we can use the drop() Method.
Syntax:
The syntax of drop() method is as below.
db.collection_name.drop()Command:
We will use the show collections commands to check the current collection list in the database. We will drop the course collection using the below command.
> db> show collections
> db.course.drop()