Create a Collection in MongoDB – Simple Guide

In this tutorial, I will explain how you can create a collection in MongoDB. This guide shall walk you through different examples to create collections in MongoDB and the different code samples

The createCollection() Syntax to Create a Collection in MongoDB

db.createCollection( name,
     capped: boolean,
     timeseries: {                  // Added in MongoDB 5.0
        timeField: string,        // required for time series collections
        metaField: string,
        granularity: string
     expireAfterSeconds: number,
     autoIndexId: boolean,
     size: number,
     max: number,
     storageEngine: document,
     validator: document,
     validationLevel: string,
     validationAction: string,
     indexOptionDefaults: document,
     viewOn: string,              // Added in MongoDB 3.4
     pipeline: pipeline,          // Added in MongoDB 3.4
     collation: document,         // Added in MongoDB 3.4
     writeConcern: document

The function has many options tied to it and allows us to create collections, capped collections, etc. Let’s look into this function in more detail.

What is a Capped Collection in MongoDB?

A capped collection in MongoDB is a collection that stores a fixed number of documents inside it and overwrites old documents with new entries every time the size limit exceeds.

To create a capped collection in MongoDB, we must set the capped option as true and also specify a minimum size of the collection in bytes by setting a value in the size option. We can also mention the minimum number of documents a capped collection can hold inside itself by setting a value for the max option.

What is a Time Series Collection?

A time-series collection is simply a collection that holds documents for a given period of time and later deletes them. We can set the expireAfterSeconds option to specify how long after should a collection be deleted after it is expired.

Using createCollection() to Create a Collection in MongoDB

The steps to create a collection in MongoDB have been made simpler with the help of the createCollection() function. Let us look at different examples so we can create a regular collection, a capped collection, a time-series collection, and a collection with document validation in MongoDB inside the mongo shell.

Creating a Regular Collection in MongoDB

Let us learn how we can create a regular collection in MongoDB from the mongo shell.

  • Start the MongoDB local database server
  • List out all the available databases and navihate to the one you want to create a collection in MongoDB
show dbs

use random
  • Now list out all the available collections before you proceed to check what all collections you have:
show tables


show collections
  • To create a collection we will now take help of the createCollection() function without any options:
> db.createCollection(`randomCollection`)
{ "ok" : 1 }

> show tables

We have created a regular collection successfully!

Creating a Capped Collection in MongoDB

Let us start with our example to create a capped collection in MongoDB. To create a collection in MongoDB that is capped, we must set a value for the capped option. I will also set values for the max and size options.

> db.createCollection("randomCappedCollection", { capped : true, size : 9999999, max : 8000 } )
{ "ok" : 1 }

> show tables

You can now see that we have a capped collection created for us.

Creating a Time Series Collection in MongoDB

Let us create a time series collection in MongoDB and take a look at its example on how to create one.

       timeseries: {
          timeField: "timestamp",
          metaField: "data",
          granularity: "hours"
       expireAfterSeconds: 14400
{ "ok" : 1 }

> show tables


We have created our first time-series collection in MongoDB that stores data every 4 hours.

Creating a Collection in MongoDB with Document Validation

Now, we will learn how to create a collection with document validation in MongoDB. The function now accepts a $jsonSchema operator in MongoDB to support JSON Schema validation.

I have borrowed this excellent example from MongoDB Docs to demonstrate it to you:

db.createCollection( "contacts", {
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "phone" ],
      properties: {
         phone: {
            bsonType: "string",
            description: "must be a string and is required"
         email: {
            bsonType : "string",
            pattern : "@mongodb\.com$",
            description: "must be a string and match the regular expression pattern"
         status: {
            enum: [ "Unknown", "Incomplete" ],
            description: "can only be one of the enum values"
   } }
} )
  • We now have a document validator that will analyze and validate our documents before inserting new ones. Let us insert an invalid document to see what error we see:
db.contacts.insert( { name: "Amanda", status: "Updated" } )

   "nInserted" : 0,
   "writeError" : {
      "code" : 121,
      "errmsg" : "Document failed validation"

Here’s what the result looks like when we try to create a collection in MongoDB that doesn’t pass the document validation test.

Read More: How to Implement Continuous Documentation for Your Developers Team


In this article, we learned to create a collection in MongoDB with the help of the different examples above. Create a regular collection, capped collection, time-series collection, and even a collection with document validation!

Noteworthy References

MongoDB Docs

Aneesha S
Aneesha S
Articles: 172