In recent years, MongoDB has retained its top spot among NoSQL databases. The term NoSQL means non-relational. Mongo is an open-source document-oriented, NoSQL Database that allows users to query data without having to know SQL. You can read more about MongoDB here.

MongoDB stores data in the form of collections. In this blog we will learn how to create a collection in MongoDB.

Prerequisites

To follow this blog, you should be having the latest version of MongoDB installed in your machine. You can download MongoDB for your operating system from this link.

Let’s start by understanding the term collection.

What is a collection in MongoDB?

We all know that MongoDB stores data in the form of documents. All the similar documents are stored in a collection. It is same as a Table in a SQL database or any of the Relational Databases.

An example of a collection is shown below:

Source: mongodb website

Each object in MongoDB is called a document. All the objects put together create a collection.

Creating a Collection in MongoDB

How to create a collection in MongoDB?

There are a couple of methods to create a collection in MongoDB:

  1. The createCollection() Method
  2. Creating the Collection in MongoDB on the fly

Let’s have a look at each of the methods one by one.

To start with we need a mongo server in our local machine. To do that, open the terminal for Mac and Linux, and PowerShell or command prompt for Windows. Run the following command.

Command: mongodThis fires up the MongoDB server.  

To run the MongoDB commands, we need to start a MongoDB shell. For this, open a new window in terminal or PowerShell or command prompt and run the following. We shall refer to this window as mongo shell in the rest of this article.

Command: mongo

This creates a shell where we can run MongoDB commands.

Let’s create a database and use it so that we can test our examples. For doing the same, run the following command in the mongo shell.

Command: use myDBThis creates a new database with the name myDB and switches to that database, so that we can work with it.

The createCollection() Method:

Using createCollection method we can create a collection which does not have any documents or an empty collection. 

The syntax of createCollection() command is as follows: 

Syntax: db.createCollection(name, options)

The createCollection method takes 2 parameters, the first parameter is the name of the collection which is a string and the other is an options object which is used to configure the collection. The options object is optional.   

To create the collection without passing the options using createCollection method, run the following command in the mongo shell. 

Command: db.createCollection(“testCollection”)This creates a collection with the name testCollection inside myDB database.

To see the collection, run the following command inside the mongo shell.

Command: show collectionsThis should show all the collections we have inside the database.

We can add additional configurations to the collection. For example, we can add validation or create a capped collection using the second parameter which is the options object.

Configuration options for creating a collection in MongoDB

The basic syntax for configuring an object in createCollection method is as shown below.

Syntax:

db.createCollection( <name>, 
   { 
     capped: <boolean>, 
     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> 
   } 
) 

Let’s look at all the options in detail.

Field Type Description
capped boolean (Optional). To create a capped collection, specify true. If you specify true, you must also set a maximum size in the size field.
autoIndexId boolean (Optional). Specify false to disable the automatic creation of an index on the _id field.
size number Optional. Specify a maximum size in bytes for a capped collection. Once a capped collection reaches its maximum size, MongoDB removes the older documents to make space for the new documents. The size field is required for capped collections and ignored for other collections.
max number Optional. The maximum number of documents allowed in the capped collection. The size limit takes precedence over this limit. If a capped collection reaches the size limit before it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use the max limit, ensure that the size limit, which is required for a capped collection, is sufficient to contain the maximum number of documents.
storageEngine document Optional. Available for the WiredTiger storage engine only.

Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection.

validator document Optional. Allows users to specify validation rules or expressions for the collection.
validationLevel string Optional. Determines how strictly MongoDB applies the validation rules to existing documents during an update.
validationAction string Optional. Determines whether to create an error on invalid documents or just warn about the violations and allow invalid documents to be inserted.
indexOptionDefaults document Optional. Allows users to specify a default configuration for indexes when creating a collection.
viewOn string The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create. You must create views in the same database as the source collection.
pipeline array An array that consists of the aggregation pipeline stage(s).

creates the view by applying the specified pipeline to the viewOn collection or view.

collation document Specifies the default collation for the collection.

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

writeConcern document Optional. A document that expresses the write concern for the operation. Omit to use the default write concern.

To know more about the options go to this link.

Example of Create Collection in MongoDB

An example for creating a collection with the options before inserting documents is shown below. Run the below command in the mongo shell.

Command: db.createCollection(“anotherCollection”, { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )

This creates a capped collection.

What is a capped collection?

A fixed-sized collection that automatically overwrites its oldest entries when it reaches its maximum size. The MongoDB oplog that is used in replication is a capped collection.

See more about capped collection and oplog over here.

Create a Collection with Document Validation

MongoDB has the capability to perform schema validation during updates and insertions. In other words, we can validate each document before updating or inserting the new documents into the collection.

To specify the validation rules for a collection we need to use db.createCollection() with the validator option.

MongoDB supports JSON Schema validation. To specify JSON Schema validation, use the $jsonSchema operator in your validator expression. This is the recommended way to perform validation in MongoDB.

What is $jsonSchema?

The $jsonSchema operator matches documents that satisfy the specified JSON Schema. It has the following syntax.

Syntax: { $jsonSchema: <JSON Schema object> }
The example for json Schema object is given below.  
Example:  

{
  $jsonSchema: {
     required: [ "name", "year", "skills", "address" ],
     properties: {
        name: {
           bsonType: "string",
           description: "must be a string and is required"
        },
        address: {
           bsonType: "object",
           required: [ "zipcode" ],
           properties: {
               "street": { bsonType: "string" },
               "zipcode": { bsonType: "string" }
           }
        }
     }
  }
}

To create a collection with validation rules, run the below command in the mongo shell.

Command:

db.createCollection("employees", { 
   validator: { 
      $jsonSchema: { 
         bsonType: "object", 
         required: [ "name", "year", "skills", "address" ], 
         properties: { 
            name: { 
               bsonType: "string", 
               description: "must be a string and is required" 
            }, 
            year: { 
               bsonType: "int", 
               minimum: 2017, 
               maximum: 2021, 
               description: "must be an integer in [ 2017, 2021] and is required" 
            }, 
            skills: { 
               enum: [ "JavaScript", "React", "Mongodb", null ], 
               description: "can only be one of the enum values and is required" 
            }, 
            salary: { 
               bsonType: [ "double" ], 
               description: "must be a double if the field exists" 
            }, 
            address: { 
               bsonType: "object", 
               required: [ "city" ], 
               properties: { 
                  street: { 
                     bsonType: "string", 
                     description: "must be a string if the field exists" 
                  }, 
                  city: { 
                     bsonType: "string", 
                     description: "must be a string and is required" 
                  } 
               } 
            } 
         } 
      } 
   } 
})

This creates a collection with validation.

Now if you run show collections command, employees collection should show up.

Now, let’s look at the second method that is “Creating the Collection in MongoDB on the fly”

Creating the Collection in MongoDB on the fly

One of the best things about MongoDB is that you need not create a collection before you insert a document in it. We can insert a document in the collection and MongoDB creates a collection on the fly. Use the below syntax to create a collection on the fly.

Syntax: db.collection_name.insert({key:value, key:value…})

Now let’s create a collection on the fly. To achieve that, run the following command in the mongo shell.

Command:

db.students.insert({
name: "Sai",
  age: 18,
  class: 10
})

This creates a collection with the name students in the database. To confirm, you can run show collections command and check. This should show all the collections which have students collection, as shown in the following image.

To check whether the document is successfully inserted, run the below command in the mongoshell to check.

Syntax: db.collection_name.find()

Command: db.students.find()

This should show all the documents inside the collection.

Conclusion

In this blog you have seen how to create a collection in MongoDB using different methods, along with examples.  

MongoDB is a rapidly growing technology nowadays as it is flexible, fast and for many more reasons. Many companies are using MongoDB as their go-to database of choice. Learning MongoDB is recommended by many of the web developers as it boosts the probability of getting a job as well.