Home > Software engineering >  How do I insert a document on a time series mongodb collection that isn’t created yet?
How do I insert a document on a time series mongodb collection that isn’t created yet?

Time:10-12

I want to insert documents into a time series collection (which will only be created when inserting a document for the first time). It's possible? Using something like db.insertOne(upsert, params) where 'params' indicates that it is a time series collection.

CodePudding user response:

There is no way of creating a time-series collection yet using the insert command if it doesn't exist.

You have to perform an if condition which checks if the collection exists beforehand and perform the insert operation.

You can make use of the findOne trick where you project only the _id key and check if a document is returned, although it will try to run the create database command even if it exists but have 0 documents in it, its way better than the List-Collection command and looping through the collections in your DB.

var foundDoc = db.collection.findOne({}, {"_id": 1});
if (foundDoc == null) {
  db.createCollection(
    "collection",
    {
       "timeseries": {
          "timeField": "timestamp",
       },
    });
}
  • Related