0
0
MongodbHow-ToBeginner · 3 min read

How to Create a Collection in MongoDB: Simple Steps

In MongoDB, you create a collection by using the db.createCollection() method or by inserting a document into a new collection. The db.createCollection() method explicitly creates a collection, while inserting a document creates the collection automatically if it doesn't exist.
📐

Syntax

The basic syntax to create a collection explicitly is:

db.createCollection(<collectionName>, <options>?)

Here:

  • <collectionName> is the name of the collection you want to create.
  • <options> is optional and can include settings like capped, size, and max.

Alternatively, inserting a document into a non-existing collection creates it automatically:

db.<collectionName>.insertOne({ key: value })
mongodb
db.createCollection("myCollection")
Output
{ "ok" : 1 }
💻

Example

This example shows how to create a collection named users explicitly and then insert a document into it.

mongodb
use myDatabase

db.createCollection("users")

db.users.insertOne({ name: "Alice", age: 30 })
Output
{ "acknowledged" : true, "insertedId" : ObjectId("someObjectId") }
⚠️

Common Pitfalls

Some common mistakes when creating collections in MongoDB include:

  • Trying to create a collection with invalid names (e.g., containing spaces or starting with system prefixes).
  • Expecting db.createCollection() to be required before inserting documents (insertion auto-creates collections).
  • Not setting options correctly for capped collections, which require size to be specified.
mongodb
/* Wrong: Missing size option for capped collection */
db.createCollection("logs", { capped: true })

/* Right: Specify size for capped collection */
db.createCollection("logs", { capped: true, size: 100000 })
Output
{ "ok" : 0, "errmsg" : "capped collections require a size" } { "ok" : 1 }
📊

Quick Reference

CommandDescription
db.createCollection(name)Explicitly creates a collection named 'name'
db.collection.insertOne(doc)Inserts a document and auto-creates collection if missing
db.createCollection(name, { capped: true, size: n })Creates a capped collection with size limit
db.collection.drop()Deletes the collection

Key Takeaways

Use db.createCollection() to explicitly create a collection with options.
Inserting a document into a new collection auto-creates it without needing createCollection().
Capped collections require a size option when created.
Avoid invalid collection names like those with spaces or starting with 'system.'.
You can drop collections with db.collection.drop() when no longer needed.