MongoDB - Create Collection
MongoDB - Create a Collection
Section titled “MongoDB - Create a 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.
The createCollection() Method
Section titled “The createCollection() Method”You use the db.createCollection(name, options) method in the MongoDB Shell (mongosh) to create a new collection.
Syntax
Section titled “Syntax”db.createCollection( <name>, { <options> } )name is a string representing the collection’s name. options is an optional document to specify configuration.
Key Options
Section titled “Key Options”| Field | Type | Description |
|---|---|---|
| capped | boolean | (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. |
| size | number | (Optional) Specifies the maximum size in bytes for a capped collection. |
| max | number | (Optional) Specifies the maximum number of documents allowed in a capped collection. |
| validator | document | (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. |
| validationLevel | string | (Optional) Determines how strictly the validator is applied to existing documents during updates. Can be "off", "strict" (default), or "moderate". |
| validationAction | string | (Optional) Determines whether to "error" (default) and reject documents that violate the rules, or just "warn" and log the violation. |
| collation | document | (Optional) Specifies language-specific rules for string comparison, such as rules for lettercase and accent marks. |
Examples
Section titled “Examples”1. Creating a Simple Collection
Section titled “1. Creating a Simple Collection”> use my_new_dbswitched to db my_new_db
> db.createCollection("users"){ "ok" : 1 }
> show collectionsusers2. 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 validationImplicit Collection Creation
Section titled “Implicit Collection Creation”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 collectionslogsstudentsusers