MongoDB Create Collection

In this article, we will see how to Create Collection in MongoDB. MongoDB collection can be created by using createCollection() method or by using insert methods(insert, inertOne or insertMany).

What is collection?

Collection is database object. It contains documents and a document contains key/value pairs.

In RDBMS(MySQL, Oracle, MS SQL Server, PostgreSQL,..) engines, we can call collection as table. Table contains columns and rows. where as MongoDB collection contains documents.

MongoDB Create Collection Syntax:

db.createCollection(, { capped: , autoIndexId: , size: , max: , storageEngine: , validator: , validationLevel: , validationAction: , indexOptionDefaults: , viewOn: , pipeline: , collation: , writeConcern: } )

Where name is the name of collection and remaining are optional parameters. For more options visit MongoDB official page

Required privileges to create MongoDB Colleciton:

  • createCollection on the database.
  • insert on the collection to create.
  • The readWrite built in role includes the required privileges.

MongoDB Create Collection Examples:

1. Create a collection using createCollection() method. Following example, creates a collection ‘student’ in the database r2schools.

> use r2schools switched to db r2schools > db.createCollection("student") { "ok" : 1 }

To verify the list of collection in the database:

> show collections student

To get the data from a collection use find() method.

db.student.find()

The above query give zero documents, because we have created empty collection.

2. Create collection in MongoDB using insert method.

> use r2schools switched to db r2schools > db.technology.insert({"name":"MongoDB","type":"NoSQL"}) WriteResult({ "nInserted" : 1 })

If we want to insert multiple documents in a collecion, we have to use [] in insert method as shown below.

> db.technology.insert([{"name":"MySQL","type":"RDBMS"},{"name":"Python","type":"Programming Languages"}])

BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })

To check the documents in the collection use the find():

> db.technology.find() { "_id" : ObjectId("5d45800522a981afe46cc99d"), "name" : "MongoDB", "type" : "NoSQL" } { "_id" : ObjectId("5d45804922a981afe46cc99e"), "name" : "MySQL", "type" : "RDBMS" } { "_id" : ObjectId("5d45804922a981afe46cc99f"), "name" : "Python", "type" : "Programming Languages" }

To verify the list of collection in the database:

> show collections student technology

We can also create fixed size collection in MongoDB. For more information about capped collection, visit What is capped collection in MongoDB