Docs Menu
Docs Home
/
Database Manual
/

Time Series Quick Start

Configure, create, and query a time series collection with MongoDB Atlas or a self-managed deployment.

Time required: 30 minutes

  • Atlas (Cloud)
  • Atlas (Local)
  • Self-Managed (On-Premises)
  • Driver
  • MongoDB Shell
  • C#
  • Java (Sync)
  • Node.js
  • Python
1
  1. Create a free Atlas account or sign in to an existing account.

  2. If you don't yet have an Atlas cluster, create a free M0 cluster. To learn more about creating an Atlas cluster, see Create a Cluster.

    Note

    You can create only one M0 Free cluster per project.

  3. In the left sidebar, click Overview. Choose your cluster and click Connect.

2
  1. Under Connect to your application, click Driver. Select C#.

    If you haven't already, follow the steps provided to download and install the .NET/C# Driver.

  2. Copy your connection string and click Done.

3
  1. Paste the following code into a new .cs file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the // start example code here and // end example code here comments.

using MongoDB.Driver;
// Replace the placeholder with your connection string.
var uri = "<connection string>";
try
{
var client = new MongoClient(uri);
// start example code here
// end example code here
}
catch (MongoException me)
{
Console.Error.WriteLine(me.Message);
}
4

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

Create a C# class to model the data in the stocks collection:

public class Stocks
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("ticker")]
public string Ticker { get; set; } = "";
[BsonElement("date")]
public DateTime Date { get; set; }
[BsonElement("close")]
public double Close { get; set; }
[BsonElement("volume")]
public double Volume { get; set; }
}
5
var db = client.GetDatabase("timeseriesdb");

This creates a reference to an empty "timeseries" database.

6
  1. Set the timeField, metaField, and granularity:

    var timeSeriesOptions = new TimeSeriesOptions(
    timeField: "date",
    metaField: "ticker",
    TimeSeriesGranularity.Seconds
    );
    var options = new CreateCollectionOptions
    {
    TimeSeriesOptions = timeSeriesOptions
    };
  2. Create the collection using the db.createCollection() method:

    db.CreateCollection("stocks", options);

    This creates an empty time series collection named stocks.

7

Use the db.collection.insertMany() method to add the following sample documents to the collection:

var stocks = db.GetCollection<Stocks>("stocks");
stocks.InsertMany(new List<Stocks>
{
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:59:00Z"),
Close = 252.47,
Volume = 55046.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:58:00Z"),
Close = 252.94,
Volume = 44042.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:57:00Z"),
Close = 253.62,
Volume = 40182.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:56:00Z"),
Close = 253.63,
Volume = 27890.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:55:00Z"),
Close = 254.03,
Volume = 40270.0
}
});

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

8

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

var query = new BsonDocument("ticker", "MDB");
var metaFieldResults = stocks.Find(query)
.Project(Builders<Stocks>.Projection.Exclude("_id"))
.ToEnumerable();
foreach (var document in metaFieldResults)
{
Console.WriteLine(document.ToJson());
}
{ "date" : { "$date" : "2021-12-18T15:55:00Z" }, "ticker" : "MDB", "volume" : 40270.0, "close" : 254.03 }
{ "date" : { "$date" : "2021-12-18T15:56:00Z" }, "ticker" : "MDB", "close" : 253.63, "volume" : 27890.0 }
{ "date" : { "$date" : "2021-12-18T15:57:00Z" }, "ticker" : "MDB", "volume" : 40182.0, "close" : 253.62 }
{ "date" : { "$date" : "2021-12-18T15:58:00Z" }, "ticker" : "MDB", "volume" : 44042.0, "close" : 252.94 }
{ "date" : { "$date" : "2021-12-18T15:59:00Z" }, "ticker" : "MDB", "volume" : 55046.0, "close" : 252.47 }

To query the timeField for a time span:

// Initialize date range
var startTime = DateTime.Parse("2021-12-18T15:50:00Z");
var endTime = DateTime.Parse("2021-12-18T15:56:00Z");
// Define the query filter
var query = new BsonDocument("$and", new BsonArray
{
new BsonDocument("date", new BsonDocument("$gte", startTime)),
new BsonDocument("date", new BsonDocument("$lte", endTime))
});
var metaFieldResults = stocks.Find(query)
.Project(Builders<Stocks>.Projection.Exclude("_id"))
.ToEnumerable();
foreach (var document in metaFieldResults)
{
Console.WriteLine(document.ToJson());
}
{"date": {"$date": "2021-12-18T15:55:00Z"}, "ticker": "MDB", "close": 254.03, "volume": 40270.0}
{"date": {"$date": "2021-12-18T15:56:00Z"}, "ticker": "MDB", "close": 253.63, "volume": 27890.0}
1

For detailed instructions, see Prerequisites.

  1. Install the Atlas CLI.

    If you use Homebrew, you can run the following command in your terminal:

    brew install mongodb-atlas-cli

    For installation instructions on other operating systems, see Install the Atlas CLI

  2. Install Docker.

    Docker requires a network connection for pulling and caching MongoDB images.

2
  1. If you don't have an existing Atlas account, run atlas setup in your terminal or create a new account.

  2. Run atlas deployments setup and follow the prompts to create a local deployment. When prompted to connect to the deployment, select skip.

    For detailed instructions, see Create a Local Atlas Deployment.

3

Follow the directions on the .NET/C# Driver Get Started page to create a new project and install driver dependencies.

4
  1. Paste the following code into a new .cs file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the // start example code here and // end example code here comments.

using MongoDB.Driver;
// Replace the placeholder with your connection string.
var uri = "<connection string>";
try
{
var client = new MongoClient(uri);
// start example code here
// end example code here
}
catch (MongoException me)
{
Console.Error.WriteLine(me.Message);
}
5

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

Create a C# class to model the data in the stocks collection:

public class Stocks
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("ticker")]
public string Ticker { get; set; } = "";
[BsonElement("date")]
public DateTime Date { get; set; }
[BsonElement("close")]
public double Close { get; set; }
[BsonElement("volume")]
public double Volume { get; set; }
}
6
var db = client.GetDatabase("timeseriesdb");

This creates a reference to an empty "timeseries" database.

7
  1. Set the timeField, metaField, and granularity:

    var timeSeriesOptions = new TimeSeriesOptions(
    timeField: "date",
    metaField: "ticker",
    TimeSeriesGranularity.Seconds
    );
    var options = new CreateCollectionOptions
    {
    TimeSeriesOptions = timeSeriesOptions
    };
  2. Create the collection using the db.createCollection() method:

    db.CreateCollection("stocks", options);

    This creates an empty time series collection named stocks.

8

Use the db.collection.insertMany() method to add the following sample documents to the collection:

var stocks = db.GetCollection<Stocks>("stocks");
stocks.InsertMany(new List<Stocks>
{
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:59:00Z"),
Close = 252.47,
Volume = 55046.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:58:00Z"),
Close = 252.94,
Volume = 44042.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:57:00Z"),
Close = 253.62,
Volume = 40182.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:56:00Z"),
Close = 253.63,
Volume = 27890.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:55:00Z"),
Close = 254.03,
Volume = 40270.0
}
});

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

9

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

var query = new BsonDocument("ticker", "MDB");
var metaFieldResults = stocks.Find(query)
.Project(Builders<Stocks>.Projection.Exclude("_id"))
.ToEnumerable();
foreach (var document in metaFieldResults)
{
Console.WriteLine(document.ToJson());
}
{ "date" : { "$date" : "2021-12-18T15:55:00Z" }, "ticker" : "MDB", "volume" : 40270.0, "close" : 254.03 }
{ "date" : { "$date" : "2021-12-18T15:56:00Z" }, "ticker" : "MDB", "close" : 253.63, "volume" : 27890.0 }
{ "date" : { "$date" : "2021-12-18T15:57:00Z" }, "ticker" : "MDB", "volume" : 40182.0, "close" : 253.62 }
{ "date" : { "$date" : "2021-12-18T15:58:00Z" }, "ticker" : "MDB", "volume" : 44042.0, "close" : 252.94 }
{ "date" : { "$date" : "2021-12-18T15:59:00Z" }, "ticker" : "MDB", "volume" : 55046.0, "close" : 252.47 }

To query the timeField for a time span:

// Initialize date range
var startTime = DateTime.Parse("2021-12-18T15:50:00Z");
var endTime = DateTime.Parse("2021-12-18T15:56:00Z");
// Define the query filter
var query = new BsonDocument("$and", new BsonArray
{
new BsonDocument("date", new BsonDocument("$gte", startTime)),
new BsonDocument("date", new BsonDocument("$lte", endTime))
});
var metaFieldResults = stocks.Find(query)
.Project(Builders<Stocks>.Projection.Exclude("_id"))
.ToEnumerable();
foreach (var document in metaFieldResults)
{
Console.WriteLine(document.ToJson());
}
{"date": {"$date": "2021-12-18T15:55:00Z"}, "ticker": "MDB", "close": 254.03, "volume": 40270.0}
{"date": {"$date": "2021-12-18T15:56:00Z"}, "ticker": "MDB", "close": 253.63, "volume": 27890.0}
1

If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.

2

Follow the directions on the .NET/C# Driver Get Started page to create a new project and install driver dependencies.

3
  1. Paste the following code into a new .cs file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the // start example code here and // end example code here comments.

using MongoDB.Driver;
// Replace the placeholder with your connection string.
var uri = "<connection string>";
try
{
var client = new MongoClient(uri);
// start example code here
// end example code here
}
catch (MongoException me)
{
Console.Error.WriteLine(me.Message);
}
4

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

Create a C# class to model the data in the stocks collection:

public class Stocks
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("ticker")]
public string Ticker { get; set; } = "";
[BsonElement("date")]
public DateTime Date { get; set; }
[BsonElement("close")]
public double Close { get; set; }
[BsonElement("volume")]
public double Volume { get; set; }
}
5
var db = client.GetDatabase("timeseriesdb");

This creates a reference to an empty "timeseries" database.

6
  1. Set the timeField, metaField, and granularity:

    var timeSeriesOptions = new TimeSeriesOptions(
    timeField: "date",
    metaField: "ticker",
    TimeSeriesGranularity.Seconds
    );
    var options = new CreateCollectionOptions
    {
    TimeSeriesOptions = timeSeriesOptions
    };
  2. Create the collection using the db.createCollection() method:

    db.CreateCollection("stocks", options);

    This creates an empty time series collection named stocks.

7

Use the db.collection.insertMany() method to add the following sample documents to the collection:

var stocks = db.GetCollection<Stocks>("stocks");
stocks.InsertMany(new List<Stocks>
{
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:59:00Z"),
Close = 252.47,
Volume = 55046.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:58:00Z"),
Close = 252.94,
Volume = 44042.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:57:00Z"),
Close = 253.62,
Volume = 40182.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:56:00Z"),
Close = 253.63,
Volume = 27890.0
},
new Stocks()
{
Ticker = "MDB",
Date = DateTime.Parse("2021-12-18T15:55:00Z"),
Close = 254.03,
Volume = 40270.0
}
});

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

8

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

var query = new BsonDocument("ticker", "MDB");
var metaFieldResults = stocks.Find(query)
.Project(Builders<Stocks>.Projection.Exclude("_id"))
.ToEnumerable();
foreach (var document in metaFieldResults)
{
Console.WriteLine(document.ToJson());
}
{ "date" : { "$date" : "2021-12-18T15:55:00Z" }, "ticker" : "MDB", "volume" : 40270.0, "close" : 254.03 }
{ "date" : { "$date" : "2021-12-18T15:56:00Z" }, "ticker" : "MDB", "close" : 253.63, "volume" : 27890.0 }
{ "date" : { "$date" : "2021-12-18T15:57:00Z" }, "ticker" : "MDB", "volume" : 40182.0, "close" : 253.62 }
{ "date" : { "$date" : "2021-12-18T15:58:00Z" }, "ticker" : "MDB", "volume" : 44042.0, "close" : 252.94 }
{ "date" : { "$date" : "2021-12-18T15:59:00Z" }, "ticker" : "MDB", "volume" : 55046.0, "close" : 252.47 }

To query the timeField for a time span:

// Initialize date range
var startTime = DateTime.Parse("2021-12-18T15:50:00Z");
var endTime = DateTime.Parse("2021-12-18T15:56:00Z");
// Define the query filter
var query = new BsonDocument("$and", new BsonArray
{
new BsonDocument("date", new BsonDocument("$gte", startTime)),
new BsonDocument("date", new BsonDocument("$lte", endTime))
});
var metaFieldResults = stocks.Find(query)
.Project(Builders<Stocks>.Projection.Exclude("_id"))
.ToEnumerable();
foreach (var document in metaFieldResults)
{
Console.WriteLine(document.ToJson());
}
{"date": {"$date": "2021-12-18T15:55:00Z"}, "ticker": "MDB", "close": 254.03, "volume": 40270.0}
{"date": {"$date": "2021-12-18T15:56:00Z"}, "ticker": "MDB", "close": 253.63, "volume": 27890.0}
1
  1. Create a free Atlas account or sign in to an existing account.

  2. If you don't yet have an Atlas cluster, create a free M0 cluster. To learn more about creating an Atlas cluster, see Create a Cluster.

    Note

    If you are working with an existing cluster, you must have Project Data Access Admin or higher access to your Atlas project.

    If you create a new cluster, you have the necessary permissions by default.

    You can create only one M0 Free cluster per project.

  3. In the left sidebar, click Overview. Choose your cluster and click Connect.

2
  1. Under Connect to your application, click Driver. Select Java (Sync).

    If you haven't already, follow the steps provided to download and install the Java Sync Driver.

  2. Copy your connection string and click Done.

3
  1. Paste the following code into a new .java file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the // start example code here and // end example code here comments.

package org.example;
// Modify imports for each tutorial as needed.
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
public class SampleApp {
public static void main(String[] args) {
// Replace the placeholder with your connection string.
String uri = "<connection string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// start example code here
// end example code here
} catch (MongoException me) {
System.err.println(me.getMessage());
}
}
}
4

Add these imports to the top of your sample app file:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.TimeSeriesGranularity;
import com.mongodb.client.model.TimeSeriesOptions;
import org.bson.Document;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
5
MongoDatabase db = mongoClient.getDatabase("timeseries_db");

This creates a reference to an empty "timeseries" database.

6

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    // Specify the time series options to configure the collection
    TimeSeriesOptions timeSeriesOptions = new TimeSeriesOptions("date")
    .metaField("ticker")
    .granularity(TimeSeriesGranularity.SECONDS);
    CreateCollectionOptions options = new CreateCollectionOptions()
    .timeSeriesOptions(timeSeriesOptions);
  2. Create the collection using the db.createCollection() method:

    db.createCollection("stocks", options);

    This creates an empty time series collection named stocks.

7

Use the db.collection.insertMany() method to add the following sample documents to the collection:

MongoCollection<Document> stocks = db.getCollection("stocks");
stocks.insertMany(
Arrays.asList(
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:59:00Z")))
.append("close", 252.47)
.append("volume", 55046.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:58:00Z")))
.append("close", 252.93)
.append("volume", 44042.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:57:00Z")))
.append("close", 253.61)
.append("volume", 40182.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:56:00Z")))
.append("close", 253.63)
.append("volume", 27890.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:55:00Z")))
.append("close", 254.03)
.append("volume", 40270.0)
)
);

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

8

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

Document query = new Document("ticker", "MDB");
FindIterable<Document> metaFieldResults = stocks.find(query)
.projection(new Document("_id", 0));
for (Document document : metaFieldResults) {
System.out.println(document.toJson());
}
{"date": {"$date": "2021-12-18T15:55:00Z"}, "ticker": "MDB", "close": 254.03, "volume": 40270.0}
{"date": {"$date": "2021-12-18T15:56:00Z"}, "ticker": "MDB", "close": 253.63, "volume": 27890.0}
{"date": {"$date": "2021-12-18T15:57:00Z"}, "ticker": "MDB", "close": 253.61, "volume": 40182.0}
{"date": {"$date": "2021-12-18T15:58:00Z"}, "ticker": "MDB", "close": 252.93, "volume": 44042.0}
{"date": {"$date": "2021-12-18T15:59:00Z"}, "ticker": "MDB", "close": 252.47, "volume": 55046.0}

To query the timeField for a time span:

// Initialize date range
Date startTime = Date.from(Instant.parse("2021-12-18T15:50:00Z"));
Date endTime = Date.from(Instant.parse("2021-12-18T15:56:00Z"));
// Define the query filter
Document query = new Document("$and", Arrays.asList(
new Document("date", new Document("$gte", startTime)),
new Document("date", new Document("$lte", endTime))
));
FindIterable<Document> metaFieldResults = stocks.find(query)
.projection(new Document("_id", 0));
for (Document document : metaFieldResults) {
System.out.println(document.toJson());
}
{"date": {"$date": "2021-12-18T15:55:00Z"}, "ticker": "MDB", "close": 254.03, "volume": 40270.0}
{"date": {"$date": "2021-12-18T15:56:00Z"}, "ticker": "MDB", "close": 253.63, "volume": 27890.0}
1

For detailed instructions, see Prerequisites.

  1. Install the Atlas CLI.

    If you use Homebrew, you can run the following command in your terminal:

    brew install mongodb-atlas-cli

    For installation instructions on other operating systems, see Install the Atlas CLI

  2. Install Docker.

    Docker requires a network connection for pulling and caching MongoDB images.

2
  1. If you don't have an existing Atlas account, run atlas setup in your terminal or create a new account.

  2. Run atlas deployments setup and follow the prompts to create a local deployment. When prompted to connect to the deployment, select skip.

    For detailed instructions, see Create a Local Atlas Deployment.

3

Follow the directions on the Java Sync Driver Get Started page to create a new project and install driver dependencies.

4
  1. Paste the following code into a new .java file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the // start example code here and // end example code here comments.

package org.example;
// Modify imports for each tutorial as needed.
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
public class SampleApp {
public static void main(String[] args) {
// Replace the placeholder with your connection string.
String uri = "<connection string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// start example code here
// end example code here
} catch (MongoException me) {
System.err.println(me.getMessage());
}
}
}
5

Add these imports to the top of your sample app file:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.TimeSeriesGranularity;
import com.mongodb.client.model.TimeSeriesOptions;
import org.bson.Document;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
6
MongoDatabase db = mongoClient.getDatabase("timeseries_db");

This creates a reference to an empty "timeseries" database.

7

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    // Specify the time series options to configure the collection
    TimeSeriesOptions timeSeriesOptions = new TimeSeriesOptions("date")
    .metaField("ticker")
    .granularity(TimeSeriesGranularity.SECONDS);
    CreateCollectionOptions options = new CreateCollectionOptions()
    .timeSeriesOptions(timeSeriesOptions);
  2. Create the collection using the db.createCollection() method:

    db.createCollection("stocks", options);

    This creates an empty time series collection named stocks.

8

Use the db.collection.insertMany() method to add the following sample documents to the collection:

MongoCollection<Document> stocks = db.getCollection("stocks");
stocks.insertMany(
Arrays.asList(
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:59:00Z")))
.append("close", 252.47)
.append("volume", 55046.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:58:00Z")))
.append("close", 252.93)
.append("volume", 44042.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:57:00Z")))
.append("close", 253.61)
.append("volume", 40182.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:56:00Z")))
.append("close", 253.63)
.append("volume", 27890.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:55:00Z")))
.append("close", 254.03)
.append("volume", 40270.0)
)
);

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

9

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

Document query = new Document("ticker", "MDB");
FindIterable<Document> metaFieldResults = stocks.find(query)
.projection(new Document("_id", 0));
for (Document document : metaFieldResults) {
System.out.println(document.toJson());
}
{"date": {"$date": "2021-12-18T15:55:00Z"}, "ticker": "MDB", "close": 254.03, "volume": 40270.0}
{"date": {"$date": "2021-12-18T15:56:00Z"}, "ticker": "MDB", "close": 253.63, "volume": 27890.0}
{"date": {"$date": "2021-12-18T15:57:00Z"}, "ticker": "MDB", "close": 253.61, "volume": 40182.0}
{"date": {"$date": "2021-12-18T15:58:00Z"}, "ticker": "MDB", "close": 252.93, "volume": 44042.0}
{"date": {"$date": "2021-12-18T15:59:00Z"}, "ticker": "MDB", "close": 252.47, "volume": 55046.0}

To query the timeField for a time span:

// Initialize date range
Date startTime = Date.from(Instant.parse("2021-12-18T15:50:00Z"));
Date endTime = Date.from(Instant.parse("2021-12-18T15:56:00Z"));
// Define the query filter
Document query = new Document("$and", Arrays.asList(
new Document("date", new Document("$gte", startTime)),
new Document("date", new Document("$lte", endTime))
));
FindIterable<Document> metaFieldResults = stocks.find(query)
.projection(new Document("_id", 0));
for (Document document : metaFieldResults) {
System.out.println(document.toJson());
}
{"date": {"$date": "2021-12-18T15:55:00Z"}, "ticker": "MDB", "close": 254.03, "volume": 40270.0}
{"date": {"$date": "2021-12-18T15:56:00Z"}, "ticker": "MDB", "close": 253.63, "volume": 27890.0}
1

If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.

2

Follow the directions on the Java Sync Driver Get Started page to create a new project and install driver dependencies.

3
  1. Paste the following code into a new .java file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the // start example code here and // end example code here comments.

package org.example;
// Modify imports for each tutorial as needed.
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
public class SampleApp {
public static void main(String[] args) {
// Replace the placeholder with your connection string.
String uri = "<connection string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// start example code here
// end example code here
} catch (MongoException me) {
System.err.println(me.getMessage());
}
}
}
4

Add these imports to the top of your sample app file:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.TimeSeriesGranularity;
import com.mongodb.client.model.TimeSeriesOptions;
import org.bson.Document;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
5
MongoDatabase db = mongoClient.getDatabase("timeseries_db");

This creates a reference to an empty "timeseries" database.

6

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    // Specify the time series options to configure the collection
    TimeSeriesOptions timeSeriesOptions = new TimeSeriesOptions("date")
    .metaField("ticker")
    .granularity(TimeSeriesGranularity.SECONDS);
    CreateCollectionOptions options = new CreateCollectionOptions()
    .timeSeriesOptions(timeSeriesOptions);
  2. Create the collection using the db.createCollection() method:

    db.createCollection("stocks", options);

    This creates an empty time series collection named stocks.

7

Use the db.collection.insertMany() method to add the following sample documents to the collection:

MongoCollection<Document> stocks = db.getCollection("stocks");
stocks.insertMany(
Arrays.asList(
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:59:00Z")))
.append("close", 252.47)
.append("volume", 55046.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:58:00Z")))
.append("close", 252.93)
.append("volume", 44042.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:57:00Z")))
.append("close", 253.61)
.append("volume", 40182.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:56:00Z")))
.append("close", 253.63)
.append("volume", 27890.0),
new Document("ticker", "MDB")
.append("date", Date.from(Instant.parse("2021-12-18T15:55:00Z")))
.append("close", 254.03)
.append("volume", 40270.0)
)
);

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

8

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

Document query = new Document("ticker", "MDB");
FindIterable<Document> metaFieldResults = stocks.find(query)
.projection(new Document("_id", 0));
for (Document document : metaFieldResults) {
System.out.println(document.toJson());
}
{"date": {"$date": "2021-12-18T15:55:00Z"}, "ticker": "MDB", "close": 254.03, "volume": 40270.0}
{"date": {"$date": "2021-12-18T15:56:00Z"}, "ticker": "MDB", "close": 253.63, "volume": 27890.0}
{"date": {"$date": "2021-12-18T15:57:00Z"}, "ticker": "MDB", "close": 253.61, "volume": 40182.0}
{"date": {"$date": "2021-12-18T15:58:00Z"}, "ticker": "MDB", "close": 252.93, "volume": 44042.0}
{"date": {"$date": "2021-12-18T15:59:00Z"}, "ticker": "MDB", "close": 252.47, "volume": 55046.0}

To query the timeField for a time span:

// Initialize date range
Date startTime = Date.from(Instant.parse("2021-12-18T15:50:00Z"));
Date endTime = Date.from(Instant.parse("2021-12-18T15:56:00Z"));
// Define the query filter
Document query = new Document("$and", Arrays.asList(
new Document("date", new Document("$gte", startTime)),
new Document("date", new Document("$lte", endTime))
));
FindIterable<Document> metaFieldResults = stocks.find(query)
.projection(new Document("_id", 0));
for (Document document : metaFieldResults) {
System.out.println(document.toJson());
}
{"date": {"$date": "2021-12-18T15:55:00Z"}, "ticker": "MDB", "close": 254.03, "volume": 40270.0}
{"date": {"$date": "2021-12-18T15:56:00Z"}, "ticker": "MDB", "close": 253.63, "volume": 27890.0}
1
  1. Create a free Atlas account or sign in to an existing account.

  2. If you don't yet have an Atlas cluster, create a free M0 cluster. To learn more about creating an Atlas cluster, see Create a Cluster.

    Note

    If you are working with an existing cluster, you must have Project Data Access Admin or higher access to your Atlas project.

    If you create a new cluster, you have the necessary permissions by default.

    You can create only one M0 Free cluster per project.

  3. In the left sidebar, click Overview. Choose your cluster and click Connect.

2
  1. Under Access your data through tools, click Shell.

    If you haven't already, follow the steps provided to download and install mongosh.

  2. Copy your connection string and click Done.

3

Use mongosh to connect to your self-managed or Atlas deployment. For example:

mongosh "mongodb+srv://my-test-cluster.1twap.mongodb.net/" --apiVersion 1
--username <user>
4
use timeseries

This creates and switches to an empty "timeseries" database.

5

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    timeseries: {
    timeField: "date",
    metaField: "ticker",
    granularity: "seconds"
    }
  2. Create the collection using the db.createCollection() method:

    db.createCollection(
    "stocks",
    {
    timeseries: {
    timeField: "date",
    metaField: "ticker",
    granularity: "seconds"
    }
    })

    This creates an empty time series collection named stocks.

6

Run the db.collection.insertMany() method to add the following sample documents to the collection:

db.stocks.insertMany([
{ ticker: "MDB", date: ISODate("2021-12-18T15:59:00.000Z"), close: 252.47, volume: 55046.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:58:00.000Z"), close: 252.93, volume: 44042.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:57:00.000Z"), close: 253.61, volume: 40182.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:56:00.000Z"), close: 253.63, volume: 27890.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:55:00.000Z"), close: 254.03, volume: 40270.00}
])

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

7

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

db.stocks.find( { ticker: "MDB" } )

To query the timeField for a time span:

db.stocks.find({ date : {
$gte : ISODate("2021-12-18T15:50:00.000Z"),
$lte : ISODate("2021-12-18T15:56:00.000Z")}
});
1

For detailed instructions, see Prerequisites.

  1. Install the Atlas CLI.

    If you use Homebrew, you can run the following command in your terminal:

    brew install mongodb-atlas-cli

    For installation instructions on other operating systems, see Install the Atlas CLI

  2. Install Docker.

    Docker requires a network connection for pulling and caching MongoDB images.

2
  1. If you don't have an existing Atlas account, run atlas setup in your terminal or create a new account.

  2. Run atlas deployments setup and follow the prompts to create a local deployment. When prompted to connect to the deployment, select skip.

    For detailed instructions, see Create a Local Atlas Deployment.

3

Go to the mongosh page and click Download mongosh. Check that the platform matches your system and click Download.

4

Use mongosh to connect to your self-managed or Atlas deployment. For example:

mongosh "mongodb+srv://my-test-cluster.1twap.mongodb.net/" --apiVersion 1
--username <user>
5
use timeseries

This creates and switches to an empty "timeseries" database.

6

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    timeseries: {
    timeField: "date",
    metaField: "ticker",
    granularity: "seconds"
    }
  2. Create the collection using the db.createCollection() method:

    db.createCollection(
    "stocks",
    {
    timeseries: {
    timeField: "date",
    metaField: "ticker",
    granularity: "seconds"
    }
    })

    This creates an empty time series collection named stocks.

7

Run the db.collection.insertMany() method to add the following sample documents to the collection:

db.stocks.insertMany([
{ ticker: "MDB", date: ISODate("2021-12-18T15:59:00.000Z"), close: 252.47, volume: 55046.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:58:00.000Z"), close: 252.93, volume: 44042.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:57:00.000Z"), close: 253.61, volume: 40182.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:56:00.000Z"), close: 253.63, volume: 27890.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:55:00.000Z"), close: 254.03, volume: 40270.00}
])

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

8

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

db.stocks.find( { ticker: "MDB" } )

To query the timeField for a time span:

db.stocks.find({ date : {
$gte : ISODate("2021-12-18T15:50:00.000Z"),
$lte : ISODate("2021-12-18T15:56:00.000Z")}
});
1

If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.

2

Go to the mongosh page and click Download mongosh. Check that the platform matches your system and click Download.

3

Use mongosh to connect to your self-managed or Atlas deployment. For example:

mongosh "mongodb+srv://my-test-cluster.1twap.mongodb.net/" --apiVersion 1
--username <user>
4
use timeseries

This creates and switches to an empty "timeseries" database.

5

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    timeseries: {
    timeField: "date",
    metaField: "ticker",
    granularity: "seconds"
    }
  2. Create the collection using the db.createCollection() method:

    db.createCollection(
    "stocks",
    {
    timeseries: {
    timeField: "date",
    metaField: "ticker",
    granularity: "seconds"
    }
    })

    This creates an empty time series collection named stocks.

6

Run the db.collection.insertMany() method to add the following sample documents to the collection:

db.stocks.insertMany([
{ ticker: "MDB", date: ISODate("2021-12-18T15:59:00.000Z"), close: 252.47, volume: 55046.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:58:00.000Z"), close: 252.93, volume: 44042.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:57:00.000Z"), close: 253.61, volume: 40182.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:56:00.000Z"), close: 253.63, volume: 27890.00},
{ ticker: "MDB", date: ISODate("2021-12-18T15:55:00.000Z"), close: 254.03, volume: 40270.00}
])

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

7

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

db.stocks.find( { ticker: "MDB" } )

To query the timeField for a time span:

db.stocks.find({ date : {
$gte : ISODate("2021-12-18T15:50:00.000Z"),
$lte : ISODate("2021-12-18T15:56:00.000Z")}
});
1
  1. Create a free Atlas account or sign in to an existing account.

  2. If you don't yet have an Atlas cluster, create a free M0 cluster. To learn more about creating an Atlas cluster, see Create a Cluster.

    Note

    If you are working with an existing cluster, you must have Project Data Access Admin or higher access to your Atlas project.

    If you create a new cluster, you have the necessary permissions by default.

    You can create only one M0 Free cluster per project.

  3. In the left sidebar, click Overview. Choose your cluster and click Connect.

2
  1. Under Connect to your application, click Driver. Select Node.js.

    If you haven't already, follow the steps provided to download and install the Node.js Driver.

  2. Copy your connection string and click Done.

3
  1. Paste the following code into a new .js file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the // start example code here and // end example code here comments.

import { MongoClient } from 'mongodb';
// Replace the placeholder with your connection string.
const uri = '<connection-string>';
const client = new MongoClient(uri);
export async function runApp() {
try {
// start example code here
// end example code here
} finally {
await client.close();
}
}
runApp().catch(console.dir);
4
const timeSeriesDB = client.db('timeseries');

This creates a reference to an empty "timeseries" database.

5

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    const options = {
    timeseries: {
    timeField: 'date',
    metaField: 'ticker',
    granularity: 'seconds',
    },
    };
  2. Create the collection using the db.createCollection() method:

    const stocks = await timeSeriesDB.createCollection('stocks', options);

    This creates an empty time series collection named stocks.

6

Use the db.collection.insertMany() method to add the following sample documents to the collection:

const sampleDocuments = [
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 59, 0, 0),
close: 252.47,
volume: 55046.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 58, 0, 0),
close: 252.93,
volume: 44042.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 57, 0, 0),
close: 253.61,
volume: 40182.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 56, 0, 0),
close: 253.63,
volume: 27890.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 55, 0, 0),
close: 254.03,
volume: 40270.0,
},
];
const result = await stocks.insertMany(sampleDocuments);

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

7

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

const metafieldResults = await stocks.find(
{ ticker: 'MDB' },
{ projection: { _id: 0 } }
);
{
date: 2021-12-18T15:55:00.000Z,
ticker: 'MDB',
volume: 40270,
close: 254.03
}
{
date: 2021-12-18T15:56:00.000Z,
ticker: 'MDB',
volume: 27890,
close: 253.63
}
{
date: 2021-12-18T15:57:00.000Z,
ticker: 'MDB',
volume: 40182,
close: 253.61,
}
{
date: 2021-12-18T15:58:00.000Z,
ticker: 'MDB',
close: 252.93,
volume: 44042
}
{
date: 2021-12-18T15:59:00.000Z,
ticker: 'MDB',
close: 252.47,
volume: 55046
}

To query the timeField for a time span:

const startTime = new Date(2021, 11, 18, 15, 50, 0, 0);
const endTime = new Date(2021, 11, 18, 15, 56, 0, 0);
const query = {
$and: [{ date: { $gte: startTime } }, { date: { $lte: endTime } }],
};
const timefieldResults = await stocks.find(query, {
projection: { _id: 0 },
});
{
date: 2021-12-18T15:55:00.000Z,
ticker: 'MDB',
close: 254.03,
volume: 40270
}
{
date: 2021-12-18T15:56:00.000Z,
ticker: 'MDB',
close: 253.63,
volume: 27890
}
1

For detailed instructions, see Prerequisites.

  1. Install the Atlas CLI.

    If you use Homebrew, you can run the following command in your terminal:

    brew install mongodb-atlas-cli

    For installation instructions on other operating systems, see Install the Atlas CLI

  2. Install Docker.

    Docker requires a network connection for pulling and caching MongoDB images.

2
  1. If you don't have an existing Atlas account, run atlas setup in your terminal or create a new account.

  2. Run atlas deployments setup and follow the prompts to create a local deployment. When prompted to connect to the deployment, select skip.

    For detailed instructions, see Create a Local Atlas Deployment.

3

Follow the directions on the Node.js Get Started page to create a new project directory and install driver dependencies.

4
  1. Paste the following code into a new .js file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the // start example code here and // end example code here comments.

import { MongoClient } from 'mongodb';
// Replace the placeholder with your connection string.
const uri = '<connection-string>';
const client = new MongoClient(uri);
export async function runApp() {
try {
// start example code here
// end example code here
} finally {
await client.close();
}
}
runApp().catch(console.dir);
5
const timeSeriesDB = client.db('timeseries');

This creates a reference to an empty "timeseries" database.

6

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    const options = {
    timeseries: {
    timeField: 'date',
    metaField: 'ticker',
    granularity: 'seconds',
    },
    };
  2. Create the collection using the db.createCollection() method:

    const stocks = await timeSeriesDB.createCollection('stocks', options);

    This creates an empty time series collection named stocks.

7

Use the db.collection.insertMany() method to add the following sample documents to the collection:

const sampleDocuments = [
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 59, 0, 0),
close: 252.47,
volume: 55046.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 58, 0, 0),
close: 252.93,
volume: 44042.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 57, 0, 0),
close: 253.61,
volume: 40182.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 56, 0, 0),
close: 253.63,
volume: 27890.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 55, 0, 0),
close: 254.03,
volume: 40270.0,
},
];
const result = await stocks.insertMany(sampleDocuments);

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

8

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

const metafieldResults = await stocks.find(
{ ticker: 'MDB' },
{ projection: { _id: 0 } }
);
{
date: 2021-12-18T15:55:00.000Z,
ticker: 'MDB',
volume: 40270,
close: 254.03
}
{
date: 2021-12-18T15:56:00.000Z,
ticker: 'MDB',
volume: 27890,
close: 253.63
}
{
date: 2021-12-18T15:57:00.000Z,
ticker: 'MDB',
volume: 40182,
close: 253.61,
}
{
date: 2021-12-18T15:58:00.000Z,
ticker: 'MDB',
close: 252.93,
volume: 44042
}
{
date: 2021-12-18T15:59:00.000Z,
ticker: 'MDB',
close: 252.47,
volume: 55046
}

To query the timeField for a time span:

const startTime = new Date(2021, 11, 18, 15, 50, 0, 0);
const endTime = new Date(2021, 11, 18, 15, 56, 0, 0);
const query = {
$and: [{ date: { $gte: startTime } }, { date: { $lte: endTime } }],
};
const timefieldResults = await stocks.find(query, {
projection: { _id: 0 },
});
{
date: 2021-12-18T15:55:00.000Z,
ticker: 'MDB',
close: 254.03,
volume: 40270
}
{
date: 2021-12-18T15:56:00.000Z,
ticker: 'MDB',
close: 253.63,
volume: 27890
}
1

If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.

2

Follow the directions on the Node.js Get Started page to create a new project directory and install driver dependencies.

3
  1. Paste the following code into a new .js file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the // start example code here and // end example code here comments.

import { MongoClient } from 'mongodb';
// Replace the placeholder with your connection string.
const uri = '<connection-string>';
const client = new MongoClient(uri);
export async function runApp() {
try {
// start example code here
// end example code here
} finally {
await client.close();
}
}
runApp().catch(console.dir);
4
const timeSeriesDB = client.db('timeseries');

This creates a reference to an empty "timeseries" database.

5

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    const options = {
    timeseries: {
    timeField: 'date',
    metaField: 'ticker',
    granularity: 'seconds',
    },
    };
  2. Create the collection using the db.createCollection() method:

    const stocks = await timeSeriesDB.createCollection('stocks', options);

    This creates an empty time series collection named stocks.

6

Use the db.collection.insertMany() method to add the following sample documents to the collection:

const sampleDocuments = [
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 59, 0, 0),
close: 252.47,
volume: 55046.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 58, 0, 0),
close: 252.93,
volume: 44042.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 57, 0, 0),
close: 253.61,
volume: 40182.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 56, 0, 0),
close: 253.63,
volume: 27890.0,
},
{
ticker: 'MDB',
date: new Date(2021, 11, 18, 15, 55, 0, 0),
close: 254.03,
volume: 40270.0,
},
];
const result = await stocks.insertMany(sampleDocuments);

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

7

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

const metafieldResults = await stocks.find(
{ ticker: 'MDB' },
{ projection: { _id: 0 } }
);
{
date: 2021-12-18T15:55:00.000Z,
ticker: 'MDB',
volume: 40270,
close: 254.03
}
{
date: 2021-12-18T15:56:00.000Z,
ticker: 'MDB',
volume: 27890,
close: 253.63
}
{
date: 2021-12-18T15:57:00.000Z,
ticker: 'MDB',
volume: 40182,
close: 253.61,
}
{
date: 2021-12-18T15:58:00.000Z,
ticker: 'MDB',
close: 252.93,
volume: 44042
}
{
date: 2021-12-18T15:59:00.000Z,
ticker: 'MDB',
close: 252.47,
volume: 55046
}

To query the timeField for a time span:

const startTime = new Date(2021, 11, 18, 15, 50, 0, 0);
const endTime = new Date(2021, 11, 18, 15, 56, 0, 0);
const query = {
$and: [{ date: { $gte: startTime } }, { date: { $lte: endTime } }],
};
const timefieldResults = await stocks.find(query, {
projection: { _id: 0 },
});
{
date: 2021-12-18T15:55:00.000Z,
ticker: 'MDB',
close: 254.03,
volume: 40270
}
{
date: 2021-12-18T15:56:00.000Z,
ticker: 'MDB',
close: 253.63,
volume: 27890
}
1
  1. Create a free Atlas account or sign in to an existing account.

  2. If you don't yet have an Atlas cluster, create a free M0 cluster. To learn more about creating an Atlas cluster, see Create a Cluster.

    Note

    If you are working with an existing cluster, you must have Project Data Access Admin or higher access to your Atlas project.

    If you create a new cluster, you have the necessary permissions by default.

    You can create only one M0 Free cluster per project.

  3. In the left sidebar, click Overview. Choose your cluster and click Connect.

2
  1. Under Connect to your application, click Driver. Select Python.

    If you haven't already, follow the steps provided to download and install the PyMongo Driver.

  2. Copy your connection string and click Done.

3
  1. Paste the following code into a new .py file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the # start example code here and # end example code here comments.

from datetime import datetime
from pymongo import MongoClient
try:
uri = "<connection-string>"
client = MongoClient(uri)
# start example code here
# end example code here
client.close()
except Exception as e:
raise Exception("The following error occurred: ", e)
4
timeseries_db = client["timeseries"]

This creates a reference to an empty "timeseries" database.

5

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    time_series_options = {
    "timeField": "date",
    "metaField": "ticker",
    "granularity": "seconds",
    }
  2. Create the collection using the db.create_collection() method:

    timeseries_db.create_collection("stocks", timeseries=time_series_options)

    This creates an empty time series collection named stocks.

6

Use the db.collection.insert_many() method to add the following sample documents to the collection:

stocks_coll = timeseries_db["stocks"]
sample_documents = [
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 59, 0, 0),
"close": 252.47,
"volume": 55046.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 58, 0, 0),
"close": 252.93,
"volume": 44042.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 57, 0, 0),
"close": 253.61,
"volume": 40182.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 56, 0, 0),
"close": 253.63,
"volume": 27890.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 55, 0, 0),
"close": 254.03,
"volume": 40270.00,
},
]
stocks_coll.insert_many(sample_documents)

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

7

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

metafield_results = stocks_coll.find({"ticker": "MDB"}, {"_id": 0})
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 55), 'close': 254.03, 'volume': 40270.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 56), 'close': 253.63, 'volume': 27890.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 57), 'close': 253.61, 'volume': 40182.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 58), 'close': 252.93, 'volume': 44042.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 59), 'close': 252.47, 'volume': 55046.0}

To query the timeField for a time span:

timefield_results = stocks_coll.find(
{
"$and": [
{"date": {"$gte": datetime(2021, 12, 18, 15, 50, 0, 0)}},
{"date": {"$lte": datetime(2021, 12, 18, 15, 56, 0, 0)}},
]
},
{"_id": 0},
)
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 55), 'close': 254.03, 'volume': 40270.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 56), 'close': 253.63, 'volume': 27890.0}
1

For detailed instructions, see Prerequisites.

  1. Install the Atlas CLI.

    If you use Homebrew, you can run the following command in your terminal:

    brew install mongodb-atlas-cli

    For installation instructions on other operating systems, see Install the Atlas CLI

  2. Install Docker.

    Docker requires a network connection for pulling and caching MongoDB images.

2
  1. If you don't have an existing Atlas account, run atlas setup in your terminal or create a new account.

  2. Run atlas deployments setup and follow the prompts to create a local deployment. When prompted to connect to the deployment, select skip.

    For detailed instructions, see Create a Local Atlas Deployment.

3

Follow the directions on the PyMongo Get Started page to create a new project directory and install driver dependencies.

4
  1. Paste the following code into a new .py file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the # start example code here and # end example code here comments.

from datetime import datetime
from pymongo import MongoClient
try:
uri = "<connection-string>"
client = MongoClient(uri)
# start example code here
# end example code here
client.close()
except Exception as e:
raise Exception("The following error occurred: ", e)
5
timeseries_db = client["timeseries"]

This creates a reference to an empty "timeseries" database.

6

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    time_series_options = {
    "timeField": "date",
    "metaField": "ticker",
    "granularity": "seconds",
    }
  2. Create the collection using the db.create_collection() method:

    timeseries_db.create_collection("stocks", timeseries=time_series_options)

    This creates an empty time series collection named stocks.

7

Use the db.collection.insert_many() method to add the following sample documents to the collection:

stocks_coll = timeseries_db["stocks"]
sample_documents = [
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 59, 0, 0),
"close": 252.47,
"volume": 55046.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 58, 0, 0),
"close": 252.93,
"volume": 44042.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 57, 0, 0),
"close": 253.61,
"volume": 40182.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 56, 0, 0),
"close": 253.63,
"volume": 27890.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 55, 0, 0),
"close": 254.03,
"volume": 40270.00,
},
]
stocks_coll.insert_many(sample_documents)

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

8

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

metafield_results = stocks_coll.find({"ticker": "MDB"}, {"_id": 0})
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 55), 'close': 254.03, 'volume': 40270.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 56), 'close': 253.63, 'volume': 27890.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 57), 'close': 253.61, 'volume': 40182.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 58), 'close': 252.93, 'volume': 44042.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 59), 'close': 252.47, 'volume': 55046.0}

To query the timeField for a time span:

timefield_results = stocks_coll.find(
{
"$and": [
{"date": {"$gte": datetime(2021, 12, 18, 15, 50, 0, 0)}},
{"date": {"$lte": datetime(2021, 12, 18, 15, 56, 0, 0)}},
]
},
{"_id": 0},
)
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 55), 'close': 254.03, 'volume': 40270.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 56), 'close': 253.63, 'volume': 27890.0}
1

If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.

2

Follow the directions on the PyMongo Get Started page to create a new project directory and install driver dependencies.

3
  1. Paste the following code into a new .py file.

  2. Replace "<connection-string>" with your copied connection string.

As you work with time series code examples, add them between the # start example code here and # end example code here comments.

from datetime import datetime
from pymongo import MongoClient
try:
uri = "<connection-string>"
client = MongoClient(uri)
# start example code here
# end example code here
client.close()
except Exception as e:
raise Exception("The following error occurred: ", e)
4
timeseries_db = client["timeseries"]

This creates a reference to an empty "timeseries" database.

5

Note

This exercise uses stock ticker sample data. The date field stores time data, and the ticker field identifies the individual stock.

  1. Set the timeField, metaField, and granularity:

    time_series_options = {
    "timeField": "date",
    "metaField": "ticker",
    "granularity": "seconds",
    }
  2. Create the collection using the db.create_collection() method:

    timeseries_db.create_collection("stocks", timeseries=time_series_options)

    This creates an empty time series collection named stocks.

6

Use the db.collection.insert_many() method to add the following sample documents to the collection:

stocks_coll = timeseries_db["stocks"]
sample_documents = [
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 59, 0, 0),
"close": 252.47,
"volume": 55046.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 58, 0, 0),
"close": 252.93,
"volume": 44042.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 57, 0, 0),
"close": 253.61,
"volume": 40182.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 56, 0, 0),
"close": 253.63,
"volume": 27890.00,
},
{
"ticker": "MDB",
"date": datetime(2021, 12, 18, 15, 55, 0, 0),
"close": 254.03,
"volume": 40270.00,
},
]
stocks_coll.insert_many(sample_documents)

If you are running MongoDB on Atlas, you can click Browse collections to view the sample data.

7

You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.

Common queries for time series data are querying the metaField to get data for a single time series, or using a range query on the timeField to get data for a given time span.

To query the metaField for a single time series:

metafield_results = stocks_coll.find({"ticker": "MDB"}, {"_id": 0})
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 55), 'close': 254.03, 'volume': 40270.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 56), 'close': 253.63, 'volume': 27890.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 57), 'close': 253.61, 'volume': 40182.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 58), 'close': 252.93, 'volume': 44042.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 59), 'close': 252.47, 'volume': 55046.0}

To query the timeField for a time span:

timefield_results = stocks_coll.find(
{
"$and": [
{"date": {"$gte": datetime(2021, 12, 18, 15, 50, 0, 0)}},
{"date": {"$lte": datetime(2021, 12, 18, 15, 56, 0, 0)}},
]
},
{"_id": 0},
)
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 55), 'close': 254.03, 'volume': 40270.0}
{'ticker': 'MDB', 'date': datetime.datetime(2021, 12, 18, 15, 56), 'close': 253.63, 'volume': 27890.0}

The following example shows the stocks time series collection structure used in this quick start.

{
_id: ObjectId(...),
ticker: <string>,
date: ISODate(...),
close: <double>,
volume: <double>
}

Time series collections are optimized for time data, so performance depends heavily on how you configure them at creation. For more information, see Time Series Collection Considerations.

Back

Time Series

On this page