How to Create MongoDB Collection

After creating a database in MongoDB, you need to create a collection, which acts as a table; this collection contains your information in the form of documents.

So, in this MongoDB tutorial, you will learn about the collection, what it is, and why to create them. Then, you will learn about two methods to create a collection.

What is MongoDB Collection?

A collection is like a table in a relational database that stores documents. The MongoDB database can have more than one collection; each collection can have more than one document.

Each document can store different types of fields or values, and the document stores data like a JSON. So, it is called a collection of documents.

There are two approaches to creating a collection in MongoDB: implicit and explicit.

Create MongoDB Collection Explicitly

To create a MongoDB collection explicitly, you need to follow the below syntax.

db.createCollection(name, options)

Where the “name” is the name of the collection that you want to assign and “options” can be the following things:

FieldTypeDescriptions
CappedBoolean(Optional) If true, it allows a capped collection. A capped collection is a fixed-size collection that overwrites its oldest entries when it reaches its maximum size. If you declare it as true, you also need to specify the size parameter.
AutoIndexIDBoolean(Optional) If true, It automatically creates the index on the _id field.
SizeNumber(Optional) For a capped collection, we have to specify the maximum size in bytes.
MaxNumber (Optional) In this, we have to specify the maximum number of documents that are allowed by capped collection.

Let’s take an example and create a collection named “employees” with different options.

db.createCollection("employees")

Using the above command, an employee collection is created in the current database, but if you want to include the options, you can follow the below command.

db.createCollection("employees", {
    capped: true,  // Creates a capped collection
    size: 5242880,  // Maximum size in bytes
    max: 5000,  // Maximum number of documents
    validationLevel: "strict",  // Validation level
    validationAction: "error",  // Action to take on validation failure
    validator: { $jsonSchema: {
        bsonType: "object",
        required: [ "name", "age" ],
        properties: {
            name: {
                bsonType: "string",
                description: "must be a string and is required"
            },
            age: {
                bsonType: "int",
                minimum: 0,
                description: "must be an integer greater than or equal to 0 and is required"
            }
        }
    }}
})

To view the collection use the command below.

show collections
Create MongoDB Collection Explicitly

From the output, you can see the collection “employees” has been created, but it is empty right now. So, using the “db.createCollection()” command you can create a new collection in your current database.

Create MongoDB Collection Implicitly

To create a MongoDB collection implicitly, you don’t need to use the db.createCollection() method. You can create a collection while inserting data.

For example the below command creates a collection named “sales” with data.

use ecommerce
db.sales.insertOne({
    item: "Laptop",
    quantity: 5,
    price: 1200,
    date: new Date("2024-05-17")
})
Create MongoDB Collection Implicitly

From the output, you can see that the collection “sales” is created using the “db.sales.inserOne()” command. While inserting data into the specified collection, MongoDB checks if it exists in the current database; if it doesn’t, it creates a new one.

Conclusion

Creating a collection is the second step in MongoDB after creating a database; as you know, a collection stores multiple documents. You learned collection is like a table in a relational database such as MySQL, SQL Server, etc.

Then, the learned collection can be created using two approaches: explicitly and implicitly.

You may like to read:

Top 200 SQL Server Interview Questions and Answers

Free PDF On Top 200 SQL Server Interview Questions And Answers

Download A 40 pages PDF And Learn Now.