Skip to content
Advertisement

How to create MongoDB Time Series Collection using pymongo

The documentation shows how to do it with mongosh, but how do you create Time Series Collection using pymongo from within a python script?

import pymongo
import time
from datetime import datetime

client = pymongo.MongoClient()
db = client['time-series-db']
col = db['time-series-col']

# ... do something here to make it 'time-series collection' ...

js = {
    "1": "A",
    "2": "B",
    "3": "C",
    "4": "D",
    "5": "E",
}

# create BSON type datetime object needed for 'time-series collection'
ts = time.time()
js['timestamp'] = datetime.utcfromtimestamp(ts)

col.insert_one(js)

Advertisement

Answer

You can try this:

conn = pymongo.MongoClient('mongodb://localhost')
db = conn.testDB

db.create_collection('testColl', timeseries={ 'timeField': 'timestamp' })
# - OR -
db.command('create', 'testColl', timeseries={ 'timeField': 'timestamp', 'metaField': 'data', 'granularity': 'hours' })

General Reference: Time Series Collections

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement