Lesson 6 +10 XP

Create a Collection

Create a Collection

A collection in MongoDB is a group of documents - the closest thing to a table in a relational database. There are two ways to create one.

Method 1: createCollection()

You can create a collection explicitly:

db.createCollection("posts")

Method 2: implicitly, with an insert

The most common way is to just insert a document. If the collection doesn't exist yet, MongoDB creates it automatically:

db.posts.insertOne({
  title: "My first post",
  body: "Hello MongoDB!"
})

This creates the posts collection if it doesn't already exist.

Same lazy pattern as databases

Just like databases, a collection isn't truly created until it has content. And like databases, collections appear under show collections once they exist:

show collections

Naming notes

  • Collection names should be meaningful and lowercase (like posts, users, orders).
  • MongoDB has naming restrictions, so keep names simple.

TL;DR

  • db.createCollection("name") creates a collection explicitly.
  • Inserting a document into a missing collection creates it automatically.
  • Collections group related documents, like tables in SQL.