Skip to main content

Creating Collections in MongoDB: Manual and Automatic Methods

Learn how collections are created in MongoDB, when to define them explicitly, and key configuration options.
Jun 22, 2025  · 5 min read

When you're working with MongoDB, especially as a developer coming from a relational database background, one of the first things you'll notice is how flexible the schema design can be.

Collections in MongoDB don’t need to be explicitly created ahead of time, but there are times when it makes sense to define them explicitly and configure them with care.

In this article, we’ll look at how and when you might want to create a collection in MongoDB, some key configuration options to consider, and some code samples in JS and C# (my favorite). 

Don’t worry, we have a lot of feature parity across drivers, so a lot of what you see here today will be possible in <insert your language of choice>.

If you're new to NoSQL databases, consider starting with an Introduction to NoSQL.

What Is a MongoDB Collection?

Before we look at how to create collections, let us briefly discuss what a collection actually is. 

If you come from a SQL background, you might be used to hearing about tables, rows, and columns. In MongoDB, the terms are slightly different. Instead of tables, we have collections, and instead of rows, we have documents with fields and not columns. 

One of the superpowers of MongoDB is its dynamic schema. That means you don’t need to create a collection manually before using it. If you insert a document into a collection that doesn’t yet exist,  MongoDB will create it automatically. For example, if you run: 

db.movies.insertOne({ title: "The Matrix", year: 1999 });

It will attempt to insert a single document for the movie “The Matrix” into the movies collection. If this already exists, the document will be added to the collection. If it doesn’t, the movies collection will be created before the new document is added.

You can also add many documents at once, using insertMany instead of insertOne.

When to Define MongoDB Collections Explicitly

Even though you can let MongoDB handle collection creation automatically, there are good reasons to define collections ahead of time, especially in production scenarios. Explicitly creating collections gives you the chance to:

  • Configure capped collections for logging or caching.
  • Set up validation rules to enforce constraints in your schemas.
  • Apply certain default indexes like time-to-live (TTL). These indexes on a date field will automatically delete documents in your collection based on an amount of time you specify.
  • Optimize for write-heavy workloads by presizing the collections.

This is how you would create a collection in the MongoDB Shell:

db.createCollection("auditLogs", {
  capped: true,
  size: 10485760, // 10 MB
  max: 1000
});

Or with validation:

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["email", "createdAt"],
      properties: {
        email: {
          bsonType: "string",
          pattern: "^.+@.+$"
        },
        createdAt: {
          bsonType: "date"
        }
      }
    }
  }
});

Although MongoDB supports a flexible schema, you may still want to add validation rules such as required fields or specifying properties on certain fields, such as data types or formatting for emails, as seen above. This is if you want to ensure that your documents do follow a specific schema. 

Schema enforcement will feel familiar if you come from a SQL background, and even if you don’t, sometimes your applications in production need to have predictably shaped documents. So validation is excellent for this!

Creating MongoDB Collections With The C# Driver

In a C# application, you can also explicitly create collections using the MongoDB driver. While it’s not required for basic operations, this is where you can set advanced options programmatically.

var options = new CreateCollectionOptions
{
    Capped = true,
    MaxSize = 10485760, // 10 MB
    MaxDocuments = 1000
};

await database.CreateCollectionAsync("auditLogs", options);

To add a validator:

var validator = new BsonDocument
{
    { "$jsonSchema", new BsonDocument
        {
            { "bsonType", "object" },
            { "required", new BsonArray { "email", "createdAt" } },
            { "properties", new BsonDocument
                {
                    { "email", new BsonDocument
                        {
                            { "bsonType", "string" },
                            { "pattern", "^.+@.+$" }
                        }
                    },
                    { "createdAt", new BsonDocument
                        {
                            { "bsonType", "date" }
                        }
                    }
                }
            }
        }
    }
};

var collectionOptions = new CreateCollectionOptions<BsonDocument>
{
    Validator = new BsonDocumentFilterDefinition<BsonDocument>(validator)
};

await database.CreateCollectionAsync("users", collectionOptions);

For Python developers, the Introduction to MongoDB and Python tutorial is a great resource.

Key Collections Configuration Options to Know

When creating collections explicitly, here are some options you may want to know:

  • capped: creates a fixed-size collection
  • size: maximum size in bytes for a capped collection
  • max: maximum number of documents allowed
  • validator: JSON object in schema syntax that defines schema validation
  • expireAfterSeconds: used with TTL indexes to handle auto-deletion of documents

You can also apply indexes at creation time or shortly after. MongoDB won’t automatically create indexes unless they’re required for _id.

Indexes in MongoDB allow you to improve the performance of your most commonly accessed fields. They will cache those values in memory, meaning no hard drive calls to retrieve, which can save a lot of time and performance when accessing these on a regular basis.

Best Practices For Defining MongoDB Collections

Here are a few guidelines to help you decide when to define collections explicitly:

  • Implicit creation for quick proof of concepts or local development, or when the end-user is able to generate the content dynamically
  • Explicit creation for when you want to apply validation or apply settings for indexing or performance

Conclusion

MongoDB is known for its flexible schema which gives us flexibility in how we structure our data, and that includes how we create and manage collections. While implicit creation is fast and convenient, explicit collection definitions unlock powerful features like schema validation, capped behavior, and performance tuning.

As always, MongoDB Atlas makes managing collections even easier with UI-based tools, automation, and built-in performance insights. And if you’re working in .NET, the C# driver has you covered with strong-typed models and fluent APIs.

When considering best practices for defining MongoDB collections, understanding fundamental database design principles can also be beneficial.

Happy coding! May your collections be fast, valid, and well-indexed!

Become a Data Engineer

Prove your skills as a job-ready data engineer.
Fast-Track My Data Career

FAQs

What is the difference between implicit and explicit collection creation in MongoDB?

  • Implicit creation: MongoDB automatically creates a collection when you insert a document into a non-existent collection. This is useful for quick prototyping or development.
  • Explicit creation: You manually define a collection before using it, often to configure advanced settings like validation rules, capped size, or indexing. This is recommended for production environments. 

When should I explicitly create a collection instead of letting MongoDB create it automatically?

You should explicitly create a collection when: schema validation, capped collections, performance optimizations, and default indexes.

How do I enforce a schema in MongoDB if it’s schema-less?

MongoDB supports JSON schema validation, which lets you define rules for document structure.

What are capped collections, and when should I use them?

Capped collections are fixed-size collections that automatically overwrite old documents when full. 

How do I create a collection with a TTL (Time-To-Live) index?

TTL indexes automatically delete documents after a specified time. First, create the collection, then add the index.


Luce Carter's photo
Author
Luce Carter
LinkedIn

Luce Carter is a Senior Developer Advocate at MongoDB, Microsoft MVP, Contentful Dev Hero, author of Beginning MongoDB Atlas with .NET, and lover of code, sunshine and learning.

Topics

Learn more about MongoDB with these courses!

Course

Introduction to MongoDB in Python

4 hr
21.8K
Learn to manipulate and analyze flexibly structured data with MongoDB.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

blog

What Is MongoDB? Key Concepts, Use Cases, and Best Practices

This guide explains MongoDB, how it works, why developers love it, and how to start using this flexible NoSQL database.
Karen Zhang's photo

Karen Zhang

15 min

blog

MongoDB Certification: A Complete Guide

Explore everything you need to know about MongoDB certification, including the types, benefits, exam preparation tips, and career opportunities.
Satyam Tripathi's photo

Satyam Tripathi

9 min

Tutorial

A Comprehensive NoSQL Tutorial Using MongoDB

Learn about NoSQL databases - why NoSQL, how they differ from relational databases, the different types, and design your own NoSQL database using MongoDB.
Arunn Thevapalan's photo

Arunn Thevapalan

9 min

Tutorial

MongoDB find(): A Complete Beginner's Guide to Querying Data

This guide explains how to use the MongoDB find() method to query, filter, sort, and paginate data with real-world examples. Perfect for beginners and those transitioning from SQL.
Samuel Molling's photo

Samuel Molling

9 min

Tutorial

Introduction to MongoDB and Python

In this tutorial, you'll learn how to integrate MongoDB with your Python applications.
Derrick Mwiti's photo

Derrick Mwiti

12 min

Tutorial

How to Use updateMany() in MongoDB to Modify Multiple Documents

Learn how to use and optimize the performance of the updateMany() operator in MongoDB to update multiple documents in a single operation.
Nic Raboy's photo

Nic Raboy

4 min

See MoreSee More