This quick start describes how to configure, create, and query a time series collection with MongoDB Atlas or a self-managed deployment.
Time required: 30 minutes
Set up your Atlas cluster.
- Create a free Atlas account or sign in to an existing account.
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.In the left sidebar, click Overview. Choose your cluster and click Connect.
Get .NET/C# Driver connection details.
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.
- Copy your connection string and click Done.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.cs
file. - 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);
}
Create a data model.
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
{
[ ]
public ObjectId Id { get; set; }
[ ]
public string Ticker { get; set; } = "";
[ ]
public DateTime Date { get; set; }
[ ]
public double Close { get; set; }
[ ]
public double Volume { get; set; }
}
Create an empty time series collection.
Set the
timeField
,metaField
, andgranularity
:var timeSeriesOptions = new TimeSeriesOptions(
timeField: "date",
metaField: "ticker",
granularity: TimeSeriesGranularity.Seconds
);
var options = new CreateCollectionOptions
{
TimeSeriesOptions = timeSeriesOptions
};Create the collection using the
db.createCollection()
method:db.CreateCollection("stocks", options);
This creates an empty time series collection named
stocks
.
Add sample documents.
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.
Query the data.
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}
Install local deployment dependencies.
For detailed instructions, see Prerequisites.
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
Install Docker.
Docker requires a network connection for pulling and caching MongoDB images.
- For MacOS or Windows, install Docker Desktop v4.31+.
- For Linux, install Docker Engine v27.0+.
- For RHEL, you can also use Podman v5.0+.
Set up your local Atlas deployment.
If you don't have an existing Atlas account, run
atlas setup
in your terminal or create a new account.Run
atlas deployments setup
and follow the prompts to create a local deployment. When prompted to connect to the deployment, selectskip
.For detailed instructions, see Create a Local Atlas Deployment.
Install the .NET/C# Driver.
Follow the directions on the .NET/C# Driver Get Started page to create a new project and install driver dependencies.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.cs
file. - 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);
}
Create a data model.
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
{
[ ]
public ObjectId Id { get; set; }
[ ]
public string Ticker { get; set; } = "";
[ ]
public DateTime Date { get; set; }
[ ]
public double Close { get; set; }
[ ]
public double Volume { get; set; }
}
Create an empty time series collection.
Set the
timeField
,metaField
, andgranularity
:var timeSeriesOptions = new TimeSeriesOptions(
timeField: "date",
metaField: "ticker",
granularity: TimeSeriesGranularity.Seconds
);
var options = new CreateCollectionOptions
{
TimeSeriesOptions = timeSeriesOptions
};Create the collection using the
db.createCollection()
method:db.CreateCollection("stocks", options);
This creates an empty time series collection named
stocks
.
Add sample documents.
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.
Query the data.
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}
Install MongoDB and local deployment dependencies.
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.
Install the .NET/C# Driver.
Follow the directions on the .NET/C# Driver Get Started page to create a new project and install driver dependencies.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.cs
file. - 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);
}
Create a data model.
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
{
[ ]
public ObjectId Id { get; set; }
[ ]
public string Ticker { get; set; } = "";
[ ]
public DateTime Date { get; set; }
[ ]
public double Close { get; set; }
[ ]
public double Volume { get; set; }
}
Create an empty time series collection.
Set the
timeField
,metaField
, andgranularity
:var timeSeriesOptions = new TimeSeriesOptions(
timeField: "date",
metaField: "ticker",
granularity: TimeSeriesGranularity.Seconds
);
var options = new CreateCollectionOptions
{
TimeSeriesOptions = timeSeriesOptions
};Create the collection using the
db.createCollection()
method:db.CreateCollection("stocks", options);
This creates an empty time series collection named
stocks
.
Add sample documents.
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.
Query the data.
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}
Set up your Atlas cluster.
- Create a free Atlas account or sign in to an existing account.
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.In the left sidebar, click Overview. Choose your cluster and click Connect.
Get Java Sync Driver connection details.
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.
- Copy your connection string and click Done.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.java
file. - 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());
}
}
}
Add the required imports.
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;
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:// 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);Create the collection using the
db.createCollection()
method:db.createCollection("stocks", options);
This creates an empty time series collection named
stocks
.
Add sample documents.
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.
Query the data.
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}
Install local deployment dependencies.
For detailed instructions, see Prerequisites.
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
Install Docker.
Docker requires a network connection for pulling and caching MongoDB images.
- For MacOS or Windows, install Docker Desktop v4.31+.
- For Linux, install Docker Engine v27.0+.
- For RHEL, you can also use Podman v5.0+.
Set up your local Atlas deployment.
If you don't have an existing Atlas account, run
atlas setup
in your terminal or create a new account.Run
atlas deployments setup
and follow the prompts to create a local deployment. When prompted to connect to the deployment, selectskip
.For detailed instructions, see Create a Local Atlas Deployment.
Install the Java Sync Driver.
Follow the directions on the Java Sync Driver Get Started page to create a new project and install driver dependencies.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.java
file. - 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());
}
}
}
Add the required imports.
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;
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:// 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);Create the collection using the
db.createCollection()
method:db.createCollection("stocks", options);
This creates an empty time series collection named
stocks
.
Add sample documents.
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.
Query the data.
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}
Install MongoDB and local deployment dependencies.
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.
Install the Java Sync Driver.
Follow the directions on the Java Sync Driver Get Started page to create a new project and install driver dependencies.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.java
file. - 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());
}
}
}
Add the required imports.
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;
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:// 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);Create the collection using the
db.createCollection()
method:db.createCollection("stocks", options);
This creates an empty time series collection named
stocks
.
Add sample documents.
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.
Query the data.
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}
Set up your Atlas cluster.
- Create a free Atlas account or sign in to an existing account.
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.In the left sidebar, click Overview. Choose your cluster and click Connect.
Get mongosh connection details.
Under Access your data through tools, click Shell.
If you haven't already, follow the steps provided to download and install
mongosh
.- Copy your connection string and click Done.
Open a new terminal window and connect to your deployment.
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>
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:timeseries: {
timeField: "date",
metaField: "ticker",
granularity: "seconds"
}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
.
Add sample documents.
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.
Query the data.
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")}
});
Install local deployment dependencies.
For detailed instructions, see Prerequisites.
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
Install Docker.
Docker requires a network connection for pulling and caching MongoDB images.
- For MacOS or Windows, install Docker Desktop v4.31+.
- For Linux, install Docker Engine v27.0+.
- For RHEL, you can also use Podman v5.0+.
Set up your local Atlas deployment.
If you don't have an existing Atlas account, run
atlas setup
in your terminal or create a new account.Run
atlas deployments setup
and follow the prompts to create a local deployment. When prompted to connect to the deployment, selectskip
.For detailed instructions, see Create a Local Atlas Deployment.
Install mongosh.
Go to the mongosh
page and click
Download mongosh. Check that the platform matches
your system and click Download.
Open a new terminal window and connect to your deployment.
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>
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:timeseries: {
timeField: "date",
metaField: "ticker",
granularity: "seconds"
}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
.
Add sample documents.
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.
Query the data.
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")}
});
Install MongoDB and local deployment dependencies.
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.
Install mongosh.
Go to the mongosh
page and click
Download mongosh. Check that the platform matches
your system and click Download.
Open a new terminal window and connect to your deployment.
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>
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:timeseries: {
timeField: "date",
metaField: "ticker",
granularity: "seconds"
}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
.
Add sample documents.
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.
Query the data.
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")}
});
Set up your Atlas cluster.
- Create a free Atlas account or sign in to an existing account.
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.In the left sidebar, click Overview. Choose your cluster and click Connect.
Get Node.js Driver connection details.
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.
- Copy your connection string and click Done.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.js
file. - 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.
const { MongoClient } = require('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);
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:const options = {
timeseries: {
timeField: 'date',
metaField: 'ticker',
granularity: 'seconds',
},
};Create the collection using the
db.createCollection()
method:const stocks = await timeSeriesDB.createCollection('stocks', options);
This creates an empty time series collection named
stocks
.
Add sample documents.
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.
Query the data.
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
}
Install local deployment dependencies.
For detailed instructions, see Prerequisites.
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
Install Docker.
Docker requires a network connection for pulling and caching MongoDB images.
- For MacOS or Windows, install Docker Desktop v4.31+.
- For Linux, install Docker Engine v27.0+.
- For RHEL, you can also use Podman v5.0+.
Set up your local Atlas deployment.
If you don't have an existing Atlas account, run
atlas setup
in your terminal or create a new account.Run
atlas deployments setup
and follow the prompts to create a local deployment. When prompted to connect to the deployment, selectskip
.For detailed instructions, see Create a Local Atlas Deployment.
Install the Node.js Driver.
Follow the directions on the Node.js Get Started page to create a new project directory and install driver dependencies.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.js
file. - 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.
const { MongoClient } = require('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);
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:const options = {
timeseries: {
timeField: 'date',
metaField: 'ticker',
granularity: 'seconds',
},
};Create the collection using the
db.createCollection()
method:const stocks = await timeSeriesDB.createCollection('stocks', options);
This creates an empty time series collection named
stocks
.
Add sample documents.
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.
Query the data.
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
}
Install MongoDB and local deployment dependencies.
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.
Install the Node.js Driver.
Follow the directions on the Node.js Get Started page to create a new project directory and install driver dependencies.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.js
file. - 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.
const { MongoClient } = require('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);
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:const options = {
timeseries: {
timeField: 'date',
metaField: 'ticker',
granularity: 'seconds',
},
};Create the collection using the
db.createCollection()
method:const stocks = await timeSeriesDB.createCollection('stocks', options);
This creates an empty time series collection named
stocks
.
Add sample documents.
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.
Query the data.
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
}
Set up your Atlas cluster.
- Create a free Atlas account or sign in to an existing account.
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.In the left sidebar, click Overview. Choose your cluster and click Connect.
Get PyMongo connection details.
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.
- Copy your connection string and click Done.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.py
file. - 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)
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:time_series_options = {
"timeField": "date",
"metaField": "ticker",
"granularity": "seconds",
}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
.
Add sample documents.
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.
Query the data.
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}
Install local deployment dependencies.
For detailed instructions, see Prerequisites.
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
Install Docker.
Docker requires a network connection for pulling and caching MongoDB images.
- For MacOS or Windows, install Docker Desktop v4.31+.
- For Linux, install Docker Engine v27.0+.
- For RHEL, you can also use Podman v5.0+.
Set up your local Atlas deployment.
If you don't have an existing Atlas account, run
atlas setup
in your terminal or create a new account.Run
atlas deployments setup
and follow the prompts to create a local deployment. When prompted to connect to the deployment, selectskip
.For detailed instructions, see Create a Local Atlas Deployment.
Install the PyMongo Driver.
Follow the directions on the PyMongo Get Started page to create a new project directory and install driver dependencies.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.py
file. - 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)
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:time_series_options = {
"timeField": "date",
"metaField": "ticker",
"granularity": "seconds",
}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
.
Add sample documents.
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.
Query the data.
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}
Install MongoDB and local deployment dependencies.
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.
Install the PyMongo Driver.
Follow the directions on the PyMongo Get Started page to create a new project directory and install driver dependencies.
Copy the template app and connect to your deployment.
- Paste the following code into a new
.py
file. - 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)
Create an empty time series collection.
Note
This exercise uses stock ticker sample data. The date
field stores time data, and
the ticker
field identifies the individual stock.
Set the
timeField
,metaField
, andgranularity
:time_series_options = {
"timeField": "date",
"metaField": "ticker",
"granularity": "seconds",
}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
.
Add sample documents.
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.
Query the data.
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}
Sample Data
This quick start creates a stocks
time series collection with the
following document structure.
{
_id: ObjectId(...),
ticker: <string>,
date: ISODate(...),
close: <double>,
volume: <double>
}
Learning Summary
This quick start focused on creating a new time series collection. Because time series collections are optimized for time data, their performance depends heavily on how you configure them at creation. For more information, see Time Series Collection Considerations.
Next Steps
To migrate existing data into a time series collection, see Migrate Data into a Time Series Collection.
- To shard a time series collection, see Shard a Time Series Collection.
For aggregation and query behaviors specific to time series collections, see Aggregation and Operator Considerations.
Learn More
To learn more about how MongoDB stores time series data internally, see About Time Series Data.
To learn more about custom bucketing parameters in MongoDB 6.3 and later, see Using Custom Bucketing Parameters.