MongoDB – Create Collection:

In mongoDB, Collection is nothing but a container of all documents.It is almost equivalent to table in RDBMS which is a combination of rows and columns. We can Create collections by using the below syntax.

Syntax:db.createCollections(name, options)
Parameter Type Description
Name string Name of the collection
Options document Optional. Configuration options for creating a capped collection, for pre-allocating space in a new collection, or for creating a view.

Example:
Use the test database and verify the database in which you are in.

testset:PRIMARY> use test
switched to db test
testset:PRIMARY>db test

Create collection called “i2tutorial” by using below command

testset:PRIMARY>db.createCollection("i2tutorial")
{ "ok" : 1 }

Check the collection which you created.

testset:PRIMARY> show collections
i2tutorial
mycollection
system.indexes

Also, you can create collections automatically by inserting a document into it.

Example:
testset:PRIMARY> show collections
i2tutorial
mycollection
system.indexes

Insert the data into the collection called ” imongo”

testset:PRIMARY>db.imongo.insert({"name":"maria","city":"Banglore"})
WriteResult({ "nInserted" : 1 })

Check if the collection imongo and the data inserted exists or not.

testset:PRIMARY> show collections
i2tutorial
imongo
mycollection
system.indexes 
testset:PRIMARY>db.imongo.find()
{ "_id" : ObjectId("5924462a5273c93ad95b109a"), "name" : "maria", "city" : "Banglore" }