MongoDB Create Collection
MongoDB Create Collection – In this MongoDB Tutorial, we shall learn ways to create a MongoDB Collection. There are both implicit and explicit ways to create a collection.
A MongoDB collection is a group of documents inside a database. In many beginner examples, you can create a collection simply by inserting the first document into it. You can also create a collection explicitly with db.createCollection() when you want to define options such as validation rules, capped collection settings, or clustered collection settings before inserting data.
Quick Comparison of Implicit and Explicit MongoDB Collection Creation
| Method | Command pattern | Use when |
|---|---|---|
| Implicit collection creation | db.collectionName.insertOne(document) | You want MongoDB to create the collection automatically when the first document is inserted. |
| Explicit collection creation | db.createCollection("collectionName") | You want to create the collection first, usually with options or validation rules. |
For small examples and simple development work, implicit creation is enough. For production applications, explicit creation is often preferred when the collection needs a known configuration before data is written.
Implicitly Create Collection in MongoDB by Inserting a Document
To create a new collection in MongoDB implicitly, follow below steps :
Step 1: Select a MongoDB database you like to Create a Collection within, using USE command. Following is the syntax of USE command.
use <database_name>
Step 2: Insert a record to Collection, with Collection Name mentioned in the command as shown below
db.<collection_name>.insert(<document>)
The collection should be created.
Step 3: View the existing collections using following command.
show collections
In current mongosh examples, insertOne() is commonly used to insert a single document. The idea is the same: if the collection does not exist, MongoDB can create it when the first document is stored.
use tutorialkart
db.customers.insertOne({
name: "Honey",
age: 25,
cars: ["Audi R8"]
})
show collections
Example 1 – Create a MongoDB Collection Automatically
Following is an example where we shall try creating a collection named customers in tutorialkart database.
Open Mongo Shell and follow the commands in sequence.
> use tutorialkart
switched to db tutorialkart
> show collections
> db.customers.insert({ name: "Honey", age: 25, cars: [ "Audi R8" ] })
WriteResult({ "nInserted" : 1 })
> show collections
customers
>
Following is the explanation for each mongodb command we executed above
- use tutorialkart switched to tutorialkart database.
- show collections lists the collections in the selected database. There are no collections at this moment.
- db.customers.insert() makes a check if the collection is present. As collection is not present yet, it creates one with the name customers specified in the command.
- show collections now lists customers collection.
The important point in this example is that the customers collection was not created with a separate command. It appeared only after the first document was inserted into db.customers.
Explicitly Create Collection in MongoDB with db.createCollection()
To create a new collection in MongoDB explicitly, follow below steps :
Step 1: Select a MongoDB database you like to Create a Collection within, using USE command. Following is the syntax of USE command.
use <database_name>
Following is the syntax of createCollection() command that creates a new collection.
db.createCollection(name, options)
where
| name | [mandatory] name of collection |
| options | [optional] mongodb document specifying information about collection |
A simple explicit collection creation command contains only the collection name.
db.createCollection("students")
If the command runs successfully, MongoDB returns an acknowledgement document.
{ ok: 1 }
You can confirm the collection by running show collections in the selected database.
MongoDB createCollection() Options for Capped Collections
Options
| Field | Type | Description |
|---|---|---|
| capped | Boolean | If true then collection is limited in size. i.e., Number of documents that could be stored in the collection is limited. |
| autoIndexId | Boolean | [depreciated] |
| size | Number | Size of Collection in Bytes |
| max | Number | Number of MongoDB Documents that could be stored in the collection |
Note#1 : All fields in Options are optional.
Note#2 : If you specify capped as true, then you should specify size.
Note#3 : When a new Document arrives Collection for insertion, size and max are the prerequisites that are verified. If the collection comes to the threshold of any, old documents are overwritten in a round robin fashion.
The autoIndexId option is shown above because it appears in older MongoDB tutorials and older shell examples. In current MongoDB usage, you should not depend on it for new code. MongoDB creates the required _id index for a collection automatically.
For a capped collection, use capped: true with a size value. The optional max value limits the number of documents, but the size limit is still required.
db.createCollection("logs", {
capped: true,
size: 1048576,
max: 5000
})
This creates a capped collection named logs. A capped collection keeps documents in insertion order and removes older documents when configured limits are reached.
View the existing collections using following command.
show collections
Example 2 – Create a MongoDB Collection with Options
Following is an example where we shall try creating a collection named myNewCollection in tutorialkart database.
Open Mongo Shell and follow the commands in sequence.
> use tutorialkart
switched to db tutorialkart
> show collections
customers
> db.createCollection("myNewCollection", { capped : true, size : 280000, max : 1000 } )
{ "ok" : 1 }
> show collections
customers
myNewCollection
>
Following is the explanation for each mongodb command we executed above
- use tutorialkart switched to tutorialkart database.
- show collections listed the collections in the selected database. There is only a collection named customers .
- db.createCollection() created new collection named myNewCollection .
- show collections now lists customers collection.
In the final step above, the selected database contains both customers and myNewCollection. The collection myNewCollection was created explicitly with capped collection options.
Create a MongoDB Collection with Document Validation
MongoDB collections are flexible by default, but you can add validation rules when the collection should accept only documents that match a required shape. Validation is useful when an application needs required fields, specific data types, or controlled field values.
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "class"],
properties: {
name: {
bsonType: "string",
description: "name must be a string and is required"
},
class: {
bsonType: "int",
description: "class must be an integer and is required"
}
}
}
}
})
With this collection definition, documents inserted into students should include the required fields in the expected types. This keeps the collection flexible, but still gives it practical rules for application data.
Check Whether a MongoDB Collection Was Created
After using either implicit or explicit collection creation, you can verify the result from mongosh.
show collections
You can also check collection details by using db.getCollectionInfos().
db.getCollectionInfos({ name: "students" })
If the array returned by this command contains collection information, the collection exists in the current database. If it returns an empty array, check whether you are using the correct database and collection name.
Common Mistakes While Creating Collections in MongoDB
- Running
db.createCollection()in the wrong database because theusecommand was not run first. - Expecting
use databaseNamealone to create a visible database or collection. The database and collection usually appear after data is stored or a collection is explicitly created. - Using a collection name with inconsistent spelling, such as
customerin one command andcustomersin another. - Creating too many collections when related documents could be stored together with a good document model.
- Using capped collection options without understanding that older documents can be removed when limits are reached.
When Should You Create a New MongoDB Collection?
Create a new collection when the data represents a separate type of document or needs different indexes, validation rules, retention behavior, or access patterns. For example, an application may use separate collections for customers, orders, and products.
Do not create separate collections only because the data would be stored in separate relational tables. MongoDB data modeling should be based on how the application reads and writes documents. In some cases, embedding related data inside one document is simpler. In other cases, separate collections and references are better.
MongoDB Create Collection FAQs
Does MongoDB automatically create collections?
Yes. MongoDB can automatically create a collection when you insert the first document into a collection name that does not already exist. You can also create a collection explicitly with db.createCollection().
How do I create a collection in MongoDB using mongosh?
Switch to the required database using use databaseName, and then run db.createCollection("collectionName"). You can verify the result with show collections.
When should I use db.createCollection() instead of insertOne()?
Use db.createCollection() when you need to define collection options before inserting data, such as validation rules or capped collection settings. Use insertOne() when automatic creation is enough for the task.
Can I create a MongoDB collection with validation rules?
Yes. You can pass a validator document to db.createCollection(). A common approach is to use $jsonSchema to require fields and control accepted BSON types.
Why is my MongoDB collection not showing after using the use command?
The use command only switches the current database context. A collection appears after you insert data into it or create it explicitly with db.createCollection().
Editorial QA Checklist for MongoDB Create Collection Tutorial
- Confirm that both implicit collection creation and explicit
db.createCollection()creation are explained clearly. - Check that existing legacy shell examples remain unchanged, while new examples use current
mongosh-friendly syntax. - Verify that capped collection options explain the need for
sizewhencappedis set totrue. - Ensure that schema validation is described as optional and useful for controlled application data.
- Check that all new code blocks use proper PrismJS classes such as
language-javascript syntaxoroutput.
Conclusion: Creating Collections in MongoDB
In this MongoDB Tutorial – MongoDB Create Collection, we learned how to create a MongoDB collection implicitly by inserting a document and explicitly by using db.createCollection(). We also covered collection options, capped collections, validation rules, verification commands, and common mistakes to avoid while creating collections.
TutorialKart.com