00:00

MongoDB Create Collection

Last updated: 5 min read

A collection is a group of documents inside a database, similar to a table in a relational database. Most of the time you never create one explicitly, because MongoDB creates it the moment you first insert a document. But when you need validation rules, time series storage, a fixed size or a special sort order, you create the collection yourself with db.createCollection().

This tutorial covers both ways, every important option, views, naming rules and the Java equivalents.

1. Implicit Creation

Writing to a collection that does not exist creates it, with default options:

mongosh
use bookstore
db.authors.insertOne({ name: "R. Mehta", country: "IN" })   // creates "authors"
db.reviews.createIndex({ bookId: 1 })                        // also creates "reviews"

show collections
// authors
// reviews

Reading from a missing collection does not create it; db.nothing.find() simply returns no documents.

2. Explicit Creation with createCollection()

Syntax
db.createCollection(<name>, <options>)

db.createCollection("customers")   // { ok: 1 }

Creating a collection that already exists with the same options succeeds silently; with different options it fails with a NamespaceExists error. The most useful options are:

OptionPurpose
validator, validationLevel, validationActionSchema validation rules and how strictly to apply them
timeseries, expireAfterSecondsCreate a time series collection and optionally expire old data
capped, size, maxFixed-size collection that overwrites the oldest documents
clusteredIndexStore documents ordered by _id (clustered collection)
collationDefault language rules for comparing and sorting strings
changeStreamPreAndPostImagesLet change streams return the document before and after each change

3. Collections with Schema Validation

Schema validation rejects documents that break your rules. The recommended way is $jsonSchema:

mongosh
db.createCollection("books", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["title", "price", "category"],
      properties: {
        title:    { bsonType: "string", minLength: 1 },
        price:    { bsonType: ["int", "double", "decimal"], minimum: 0 },
        category: { enum: ["Java", "Database", "Kafka", "Cloud"] },
        tags:     { bsonType: "array", items: { bsonType: "string" } }
      }
    }
  },
  validationLevel: "strict",     // check every insert and update
  validationAction: "error"      // reject invalid documents ("warn" only logs them)
})

db.books.insertOne({ title: "Untitled", price: -5, category: "Java" })
// MongoServerError: Document failed validation
SettingValues
validationLevel"strict" (all writes, default), "moderate" (skip existing documents that were already invalid), "off"
validationAction"error" (reject, default) or "warn" (accept but log)

You can add or change rules later on an existing collection with collMod:

mongosh
db.runCommand({ collMod: "books", validator: { $jsonSchema: { required: ["title", "price"] } } })

4. Time Series Collections

Time series collections are built for measurements over time. MongoDB groups readings from the same source into compressed buckets, which greatly reduces storage and speeds up time-range queries.

mongosh
db.createCollection("temperatures", {
  timeseries: {
    timeField: "ts",          // required: the timestamp field
    metaField: "sensor",      // optional: what identifies the source
    granularity: "minutes"    // "seconds", "minutes" or "hours"
  },
  expireAfterSeconds: 2592000 // optional: delete data older than 30 days
})

db.temperatures.insertOne({ ts: new Date(), sensor: { id: "S-17", room: "lab" }, celsius: 22.4 })

5. Capped Collections

A capped collection has a fixed maximum size. When it is full, the oldest documents are overwritten, so it behaves like a circular buffer and keeps documents in insertion order.

mongosh
db.createCollection("recentEvents", {
  capped: true,
  size: 10 * 1024 * 1024,   // required: maximum size in bytes (10 MB)
  max: 50000                // optional: maximum number of documents
})

db.recentEvents.isCapped()   // true
Capped collections cannot be sharded. For most "keep only recent data" needs, a normal collection with a TTL index or a time series collection with expireAfterSeconds is the more flexible choice.

6. Clustered Collections

In a clustered collection, documents are stored in _id order, so the collection itself acts as the _id index. Range queries and deletes on _id are efficient, and storage is lower because there is no separate _id index.

mongosh
db.createCollection("orderEvents", {
  clusteredIndex: { key: { _id: 1 }, unique: true, name: "events by id" }
})

7. Collections with a Default Collation

A collation sets language-aware rules for string comparison. For example, a strength of 2 makes queries and sorting case-insensitive:

mongosh
db.createCollection("users", { collation: { locale: "en", strength: 2 } })

db.users.insertOne({ username: "Aditi" })
db.users.find({ username: "aditi" })   // matches, because comparison ignores case

8. Views

A view is a read-only, collection-like object defined by an aggregation pipeline on another collection. It stores no data of its own and is calculated when you query it.

mongosh
db.createView("cheapJavaBooks", "books", [
  { $match: { category: "Java", price: { $lt: 500 } } },
  { $project: { _id: 0, title: 1, price: 1 } }
])

db.cheapJavaBooks.find()

9. Listing and Inspecting Collections

mongosh
show collections
db.getCollectionNames()
db.getCollectionInfos({ name: "books" })   // options, validator, type (collection, view, timeseries)
db.books.stats()                          // size, document count, index sizes

10. Collection Naming Rules

  • Must not be empty and must not contain the null character or $.
  • Must not start with system., which is reserved for internal collections.
  • The full namespace database.collection must be at most 255 bytes.
  • Names are case-sensitive: Books and books are different collections.
  • Use consistent, readable names such as lowercase plural nouns: books, orders, order_events.
Names with hyphens or spaces work, but cannot be used with dot syntax in mongosh. Use db.getCollection("order-events") or, better, avoid such names.

11. Creating Collections from Java

CreateCollectionsExample.java
import com.mongodb.client.*;
import com.mongodb.client.model.*;
import org.bson.Document;
import java.util.concurrent.TimeUnit;

public class CreateCollectionsExample {
    public static void main(String[] args) {
        try (MongoClient client = MongoClients.create("mongodb://localhost:27017")) {
            MongoDatabase db = client.getDatabase("bookstore");

            // Collection with validation
            Document schema = Document.parse("""
                { "$jsonSchema": { "bsonType": "object", "required": ["title", "price"] } }
                """);
            db.createCollection("books", new CreateCollectionOptions()
                    .validationOptions(new ValidationOptions().validator(schema)
                            .validationAction(ValidationAction.ERROR)));

            // Time series collection with 30-day expiry
            db.createCollection("temperatures", new CreateCollectionOptions()
                    .timeSeriesOptions(new TimeSeriesOptions("ts").metaField("sensor")
                            .granularity(TimeSeriesGranularity.MINUTES))
                    .expireAfter(30, TimeUnit.DAYS));

            // Capped collection of 10 MB
            db.createCollection("recentEvents", new CreateCollectionOptions()
                    .capped(true).sizeInBytes(10L * 1024 * 1024));
        }
    }
}

12. Summary

  • Collections are created automatically by the first insert or index creation.
  • Use db.createCollection() when you need options: validation, time series, capped size, clustering, collation or change stream images.
  • $jsonSchema validation adds structure to a flexible schema and can be changed later with collMod.
  • Views are read-only, pipeline-based collections that store no data.
  • Follow the naming rules and keep names lowercase and consistent.