liveBook · Manning

Db.createCollection()

As explained in MongoDB 8.0 in Action, Third Edition

db.createCollection() is the MongoDB database method that explicitly creates a collection and accepts collection options such as capped, time-series, and validation settings.

db.createCollection() explicitly creates a MongoDB collection when you need collection-level options, such as capped storage, time-series behavior, or document validation. Without those options, MongoDB generally creates the collection when data is first stored. section 2.6.3

Use explicit creation when collection behavior or deployment constraints require it:

  • Configure capped or time-series collections and define their storage or time-field settings. section 2.6.3
  • Apply document validation rules during collection creation. section 2.6.3
  • Avoid manual creation for ordinary collections unless controlled initialization is useful; insertOne() and createIndex() can create collections implicitly. section 2.6.3
  • Respect collection-name restrictions: names cannot be empty, contain the null character or dollar sign, or begin with the reserved system prefix. section 2.6.3
  • Keep explicit collection creation outside cross-shard write transactions and transactions using a read concern other than local. section 8.5

Create a time-series collection

Run this in mongosh to create a collection whose measurements use timestamp as the time field and metadata as the metadata field: db.createCollection( "my_time_series_collection", { timeseries: { timeField: "timestamp", metaField: "metadata" } } ) section 2.6.3

Listing 2.4 Creating a time-series collection
db.createCollection(
"my_time_series_collection",
{
  timeseries: {
  timeField: "timestamp",
  metaField: "metadata"
}})

Inspect the complete time-series creation command and its option structure. section 2.6.3

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Explains options, naming restrictions, implicit creation, and transaction prohibitions without detailing server internals.
Examples
Demonstrates creating a time-series collection with timestamp and metadata fields.
What it assumes
Assumes familiarity with MongoDB collections and mongosh while clarifying ordinary collection creation from zero.
What you can do after
Operate/configure collections with explicit options and recognize when MongoDB will create them implicitly.
How it connects
Connects collections with time-series collections, document validation, indexes, namespaces, and transactions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.