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
