Skip to content

MongoDB - Create Collection

In MongoDB, a collection is a group of documents, analogous to a table in a relational database. While MongoDB can create collections implicitly the first time you insert a document, it is a best practice in production to create them explicitly to enforce schema validation and other configurations.

You use the db.createCollection(name, options) method in the MongoDB Shell (mongosh) to create a new collection.

db.createCollection( <name>, { <options> } )

name is a string representing the collection’s name. options is an optional document to specify configuration.

FieldTypeDescription
cappedboolean(Optional) If true, creates a capped collection, which is a fixed-size collection that automatically overwrites its oldest entries when it reaches its maximum size. Requires the size option.
sizenumber(Optional) Specifies the maximum size in bytes for a capped collection.
maxnumber(Optional) Specifies the maximum number of documents allowed in a capped collection.
validatordocument(Optional) A powerful feature that allows you to specify JSON Schema validation rules for your collection. Inserts and updates that violate these rules will be rejected.
validationLevelstring(Optional) Determines how strictly the validator is applied to existing documents during updates. Can be "off", "strict" (default), or "moderate".
validationActionstring(Optional) Determines whether to "error" (default) and reject documents that violate the rules, or just "warn" and log the violation.
collationdocument(Optional) Specifies language-specific rules for string comparison, such as rules for lettercase and accent marks.
> use my_new_db
switched to db my_new_db
> db.createCollection("users")
{ "ok" : 1 }
> show collections
users

2. Creating a Collection with Schema Validation (Best Practice)

Section titled “2. Creating a Collection with Schema Validation (Best Practice)”

This is the recommended approach for production systems. It ensures data consistency and quality.

> db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "gpa" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
year: {
bsonType: "int",
minimum: 1,
maximum: 5,
description: "must be an integer in [1, 5] and is required"
},
major: {
bsonType: "string",
description: "must be a string and is required"
},
gpa: {
bsonType: ["double", "int"],
description: "must be a number and is required"
}
}
}
}
})
{ "ok" : 1 }

Now, if you try to insert a document that doesn’t conform to this schema, MongoDB will reject it:

> db.students.insertOne({ name: "John Doe", major: "Computer Science" })
// This will fail because 'year' and 'gpa' are missing.
MongoServerError: Document failed validation

If you insert a document into a collection that doesn’t exist, MongoDB creates it for you automatically. This is convenient for development but not recommended for production.

> db.logs.insertOne({ timestamp: new Date(), message: "User logged in." })
{
acknowledged: true,
insertedId: ObjectId("...")
}
> show collections
logs
students
users