MongoDB Academy · Урок

Создание коллекции временных рядов

Вы создадите коллекцию временных рядов, указав параметры timeField, metaField и детализации.

Урок 1 из 413 шагов

«Создание коллекции временных рядов» — бесплатный урок MongoDB Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения MongoDB Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс MongoDB Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Introduction to Time Series Collections

MongoDB 5.0 introduced native time series collections — a specialised collection type optimised for storing and querying measurements that change over time. Common use cases include IoT sensor readings, application metrics, financial ticks, and server monitoring data. Unlike regular collections, time series collections use a columnar storage format internally, dramatically reducing storage space and improving query performance on time-range filters.

Key Fields: timeField, metaField, granularity

Every time series collection requires three key options when created. The timeField is the document field that holds the timestamp (must be a BSON Date). The metaField identifies the series — for example, a sensor ID or device name. The granularity hint ('seconds', 'minutes', or 'hours') tells MongoDB how frequently measurements arrive, allowing it to optimise bucket sizing internally.

Creating With createCollection Command

Use db.createCollection() with a timeseries option object to create a time series collection. You cannot convert an existing regular collection to time series — you must create it fresh. The collection will appear in show collections with a special timeseries type indicator.

db.createCollection('sensorReadings', {
  timeseries: {
    timeField: 'timestamp',
    metaField: 'sensorId',
    granularity: 'seconds'
  }
})

Granularity Affects Bucket Sizing

The granularity option controls how MongoDB groups measurements into internal bucket documents. With 'seconds', buckets span one hour (3,600 measurements per bucket). With 'minutes', buckets span 24 hours. With 'hours', buckets span 30 days. Choosing the wrong granularity means more bucket documents and worse compression — always match granularity to your actual data arrival rate.

// Sensor sends data every second — use 'seconds'
db.createCollection('iotData', {
  timeseries: {
    timeField: 'ts',
    metaField: 'device',
    granularity: 'seconds'
  }
})

// Aggregated hourly metric — use 'hours'
db.createCollection('hourlyMetrics', {
  timeseries: {
    timeField: 'ts',
    metaField: 'service',
    granularity: 'hours'
  }
})

Document Shape for Time Series Inserts

Documents inserted into a time series collection must include the timeField as a proper BSON Date. The metaField value identifies which series this measurement belongs to (e.g., a device ID). All other fields are called measurement fields and can hold any BSON value. MongoDB will reject documents where the timeField is missing or not a Date.

// Valid time series document
{
  timestamp: new Date(),   // timeField — must be a Date
  sensorId: 'sensor-42',  // metaField — identifies the series
  temperature: 23.7,       // measurement field
  humidity: 55.2,          // measurement field
  pressure: 1013.4         // measurement field
}

Inserting Single and Multiple Measurements

Insert into a time series collection exactly as you would a regular collection — using insertOne() or insertMany(). MongoDB handles the internal bucketing automatically. It is best practice to batch inserts with insertMany() when loading historical data, as this amortises the overhead of bucket creation across many measurements.

// Insert a single measurement
db.sensorReadings.insertOne({
  timestamp: new Date('2024-06-01T10:00:00Z'),
  sensorId: 'sensor-42',
  temperature: 22.5,
  humidity: 60.1
})

// Bulk insert historical data
db.sensorReadings.insertMany([
  { timestamp: new Date('2024-06-01T10:01:00Z'), sensorId: 'sensor-42', temperature: 22.6, humidity: 60.0 },
  { timestamp: new Date('2024-06-01T10:02:00Z'), sensorId: 'sensor-42', temperature: 22.4, humidity: 60.3 }
])

Adding Automatic Expiration With expireAfterSeconds

Time series collections support automatic data expiration via the expireAfterSeconds option. Once set, MongoDB's background TTL thread deletes entire buckets when all measurements in the bucket are older than the threshold. This is more efficient than a regular TTL index because entire internal bucket documents are dropped at once rather than individual measurement documents.

// Create with 90-day TTL
db.createCollection('sensorReadings', {
  timeseries: {
    timeField: 'timestamp',
    metaField: 'sensorId',
    granularity: 'minutes'
  },
  expireAfterSeconds: 60 * 60 * 24 * 90  // 90 days
})

Querying Time Series Collections

Queries on time series collections look identical to regular find() queries. MongoDB automatically uses the internal bucket structure to skip irrelevant buckets when filtering by time range. Filtering on the metaField is also highly efficient. Avoid querying only on measurement fields without a time or meta filter, as this forces a full collection scan across all buckets.

// Query last 24 hours for a specific sensor
const since = new Date(Date.now() - 24 * 60 * 60 * 1000)

db.sensorReadings.find({
  sensorId: 'sensor-42',
  timestamp: { $gte: since }
}).sort({ timestamp: 1 })

Updating the Granularity After Creation

You can increase the granularity of an existing time series collection (e.g., from 'seconds' to 'minutes') using the collMod command. However, you cannot decrease it — MongoDB will return an error if you try to move from 'minutes' back to 'seconds'. Updating the expireAfterSeconds setting is also possible via collMod without recreating the collection.

// Increase granularity from seconds to minutes
db.runCommand({
  collMod: 'sensorReadings',
  timeseries: { granularity: 'minutes' }
})

// Update expireAfterSeconds to 30 days
db.runCommand({
  collMod: 'sensorReadings',
  expireAfterSeconds: 60 * 60 * 24 * 30
})

Limitations and Restrictions

Time series collections have a few important restrictions compared to regular collections. You cannot shard a time series collection on the timeField alone — a hashed metaField component is required. Updates and deletes are limited: before MongoDB 5.1, only deletes by metaField or time range were supported. Additionally, time series collections do not support unique indexes, sparse indexes, or capped collections.

Verifying Collection Type and Options

After creating a time series collection, inspect it using db.getCollectionInfos() to confirm the timeseries options are correctly stored. You can also run db.sensorReadings.stats() to see storage statistics, including the number of internal bucket documents MongoDB is maintaining behind the scenes.

// Inspect time series collection metadata
db.getCollectionInfos({ name: 'sensorReadings' })

// Check storage stats
db.sensorReadings.stats()

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: time series collections use a columnar bucket format for high-compression append-heavy workloads, three key options (timeField, metaField, granularity) control how measurements are organised and bucketed, and expireAfterSeconds enables efficient automatic purging of old data at the bucket level. Next up we explore inserting and querying time series data in depth.

Можно начать бесплатно

Изучай JavaScript с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
30
Уроки
120

Часто задаваемые вопросы

Урок «Создание коллекции временных рядов» бесплатный?

Да — полный текст урока «Создание коллекции временных рядов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс MongoDB Academy, подпишись на CoddyKit PRO. Курс MongoDB Academy содержит 4 уроков всего.

Чему я научусь в уроке «Создание коллекции временных рядов»?

Вы создадите коллекцию временных рядов, указав параметры timeField, metaField и детализации. Ты практикуешь MongoDB Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать MongoDB Academy?

Предыдущий опыт не требуется. MongoDB Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Создание коллекции временных рядов»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке MongoDB Academy?

Да. Каждый урок MongoDB Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Создание коллекции временных рядов
  2. Вставка и запрос данных временных рядов
  3. Оконная агрегация временных рядов
  4. Автоматическое удаление данных с помощью expireAfterSeconds
← Назад к MongoDB Academy