This quick start describes how to configure, create, and query a time series collection with MongoDB Atlas or a self-managed deployment.本快速入门介绍了如何使用MongoDB Atlas或自我管理部署配置、创建和查询时间序列集合。
Time required: 30 minutes所需时间:30分钟
C#
Atlas(Cloud)
Set up your Atlas cluster.设置Atlas集群。
Create a free Atlas account or sign in to an existing account.创建一个免费的Atlas帐户或登录现有帐户。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.如果您还没有Atlas集群,请创建一个免费的M0集群。要了解有关创建Atlas集群的更多信息,请参阅创建集群。Note
If you are working with an existing cluster, you must have如果您使用的是现有集群,则必须具有投影数据访问管理员或更高级别的Atlas项目访问权限。Project Data Access Adminor higher access to your Atlas project.If you create a new cluster, you have the necessary permissions by default.如果创建新集群,默认情况下您具有必要的权限。You can create only one每个项目只能创建一个M0Free cluster per project.M0免费集群。In the left sidebar, click Overview. Choose your cluster and click Connect.在左侧边栏中,单击概述。选择集群,然后单击连接。
Get .NET/C# Driver connection details.获取.NET/C#驱动程序连接详细信息。
Under Connect to your application, click Driver. Select C#.在“连接到应用程序”下,单击“驱动程序”。选择C#。If you haven't already, follow the steps provided to download and install the .NET/C# Driver.如果您还没有,请按照提供的步骤下载并安装.NET/C#驱动程序。Copy your connection string and click Done.复制连接字符串,然后单击“完成”。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到新的.csfile..cs文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到// start example code here and // end example code here comments.// start example code here和// end example code here注释之间。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Create a C# class to model the data in the 创建一个C#类来对stocks collection:stocks(股票)集合中的数据进行建模:
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; }
}Access the database.访问数据库。
var db = client.GetDatabase("timeseriesdb");
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
Create an empty time series collection.创建一个空的时间序列集合。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity: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()方法创建集合:db.CreateCollection("stocks", options);This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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:timeField中查询时间跨度,请执行以下操作:
// 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}
Atlas(local)
Install local deployment dependencies.安装本地部署依赖项。
For detailed instructions, see Prerequisites.有关详细说明,请参阅先决条件。
Install the Atlas CLI.安装Atlas CLI。If you use Homebrew, you can run the following command in your terminal:如果您使用Homebrew,您可以在终端中运行以下命令:brew install mongodb-atlas-cliFor installation instructions on other operating systems, see Install the Atlas CLI有关其他操作系统上的安装说明,请参阅安装Atlas CLI-
Docker requires a network connection for pulling and caching MongoDB images.Docker需要网络连接来拉取和缓存MongoDB映像。For MacOS or Windows, install Docker Desktop v4.31+.对于MacOS或Windows,请安装Docker Desktop v4.31+。For Linux, install Docker Engine v27.0+.对于Linux,请安装Docker Engine v27.0+。For RHEL, you can also use Podman v5.0+.对于RHEL,您还可以使用Podman v5.0+。
Set up your local Atlas deployment.设置本地Atlas部署。
If you don't have an existing Atlas account, run如果您没有现有的Atlas帐户,请在终端中运行atlas setupin your terminal or create a new account.atlas setup或创建新帐户。Run运行“Atlas部署设置程度”,并按照提示创建本地部署。当系统提示连接到部署时,选择“跳过”。atlas deployments setupand 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.有关详细说明,请参阅创建本地Atlas部署。
Install the .NET/C# Driver.安装.NET/C#驱动程序。
Follow the directions on the .NET/C# Driver Get Started page to create a new project and install driver dependencies.按照.NET/C#驱动程序入门页面上的说明创建新项目并安装驱动程序依赖项。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到新的.csfile..cs文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到// start example code here and // end example code here comments.// start example code here和// end example code here注释之间。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Create a C# class to model the data in the 创建一个C#类来对stocks collection:stocks(股票)集合中的数据进行建模:
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; }
}Access the database.访问数据库。
var db = client.GetDatabase("timeseriesdb");
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
Create an empty time series collection.创建一个空的时间序列集合。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity: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()方法创建集合:db.CreateCollection("stocks", options);This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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:timeField中查询时间跨度,请执行以下操作:
// 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}
Self-Managed(on-Premises)
Install MongoDB and local deployment dependencies.安装MongoDB和本地部署依赖项。
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.如果您正在运行自我管理部署,请按照MongoDB版本、版本和平台的安装说明进行操作。
Install the .NET/C# Driver.安装.NET/C#驱动程序。
Follow the directions on the .NET/C# Driver Get Started page to create a new project and install driver dependencies.按照.NET/C#驱动程序入门页面上的说明创建新项目并安装驱动程序依赖项。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到新的.cs文件中。.csfile.Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到// start example code here and // end example code here comments.// start example code here和// end example code here注释之间。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Create a C# class to model the data in the 创建一个C#类来对stocks collection:stocks(股票)集合中的数据进行建模:
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; }
}Access the database.访问数据库。
var db = client.GetDatabase("timeseriesdb");
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
Create an empty time series collection.创建一个空的时间序列集合。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity: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()方法创建集合:db.CreateCollection("stocks", options);This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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:timeField中查询时间跨度,请执行以下操作:
// 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}
Java(sync)
Atlas(Cloud)
Set up your Atlas cluster.设置Atlas集群。
Create a free Atlas account or sign in to an existing account.创建一个免费的Atlas帐户或登录现有帐户。If you don't yet have an Atlas cluster, create a free M0 cluster.如果您还没有Atlas集群,请创建一个免费的M0集群。To learn more about creating an Atlas cluster, see Create a Cluster.要了解有关创建Atlas集群的更多信息,请参阅创建集群。Note
If you are working with an existing cluster, you must have如果您使用的是现有集群,则必须具有投影数据访问管理员或更高级别的Atlas项目访问权限。Project Data Access Adminor higher access to your Atlas project.If you create a new cluster, you have the necessary permissions by default.如果创建新集群,默认情况下您具有必要的权限。You can create only one每个项目只能创建一个M0Free cluster per project.M0免费集群。In the left sidebar, click Overview. Choose your cluster and click Connect.在左侧边栏中,单击概述。选择集群,然后单击“连接”。
Get Java Sync Driver connection details.获取Java同步驱动程序连接详细信息。
Under Connect to your application, click Driver. Select Java (Sync).在“连接到应用程序”下,单击“驱动程序”。选择Java(同步)。If you haven't already, follow the steps provided to download and install the Java Sync Driver.如果您还没有,请按照提供的步骤下载并安装Java同步驱动程序。Copy your connection string and click Done.复制连接字符串,然后单击“完成”。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到一个新的.javafile..java文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到// start example code here and // end example code here comments.// start example code here和// end example code here注释之间。
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;Access the database.访问数据库。
MongoDatabase db = mongoClient.getDatabase("timeseries_db");
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和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);Create the collection using the使用db.createCollection()method:db.createCollection()方法创建集合:db.createCollection("stocks", options);This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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:timeField中查询时间跨度,请执行以下操作:
// 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}
Atlas(local)
Install local deployment dependencies.安装本地部署依赖项。
For detailed instructions, see Prerequisites.有关详细说明,请参阅先决条件。
Install the Atlas CLI.安装Atlas CLI。If you use Homebrew, you can run the following command in your terminal:如果您使用Homebrew,您可以在终端中运行以下命令:brew install mongodb-atlas-cliFor installation instructions on other operating systems, see Install the Atlas CLI有关其他操作系统上的安装说明,请参阅安装Atlas CLI-
Docker requires a network connection for pulling and caching MongoDB images.Docker需要网络连接来拉取和缓存MongoDB映像。For MacOS or Windows, install Docker Desktop v4.31+.对于MacOS或Windows,请安装Docker Desktop v4.31+。For Linux, install Docker Engine v27.0+.对于Linux,请安装Docker Engine v27.0+。For RHEL, you can also use Podman v5.0+.对于RHEL,您还可以使用Podman v5.0+。
Set up your local Atlas deployment.设置本地Atlas部署。
If you don't have an existing Atlas account, run如果您没有现有的Atlas帐户,请在终端中运行atlas setupin your terminal or create a new account.atlas setup或创建新帐户。Run运行“atlas部署设置程序”,并按照提示创建本地部署。当系统提示连接到部署时,选择“跳过”。atlas deployments setupand 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.有关详细说明,请参阅创建本地Atlas部署。
Install the Java Sync Driver.安装Java同步驱动程序。
Follow the directions on the Java Sync Driver Get Started page to create a new project and install driver dependencies.按照Java同步驱动程序入门页面上的说明创建新项目并安装驱动程序依赖项。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到一个新的.javafile..java文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到// start example code here and // end example code here comments.// start example code here和// end example code here注释之间。
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;Access the database.访问数据库。
MongoDatabase db = mongoClient.getDatabase("timeseries_db");
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
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.date字段存储时间数据,股票代码字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和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);Create the collection using the使用db.createCollection()method:db.createCollection()方法创建集合:db.createCollection("stocks", options);This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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:timeField中查询时间跨度,请执行以下操作:
// 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}
Self-Managed(on-Premises)
Install MongoDB and local deployment dependencies.安装MongoDB和本地部署依赖项。
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.如果您正在运行自我管理部署,请按照MongoDB版本、版本和平台的安装说明进行操作。
Install the Java Sync Driver.安装Java同步驱动程序。
Follow the directions on the Java Sync Driver Get Started page to create a new project and install driver dependencies.按照“Java同步驱动程序入门”页面上的说明创建新项目并安装驱动程序依赖项。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到一个新的.javafile..java文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到// start example code here and // end example code here comments.// start example code here和// end example code here注释之间。
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;Access the database.访问数据库。
MongoDatabase db = mongoClient.getDatabase("timeseries_db");
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和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);Create the collection using the使用db.createCollection()method:db.createCollection()方法创建集合:db.createCollection("stocks", options);This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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:timeField中查询时间跨度,请执行以下操作:
// 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}
Mongosh
Atlas(Cloud)
Set up your Atlas cluster.设置Atlas集群。
Create a free Atlas account or sign in to an existing account.创建一个免费的Atlas帐户或登录现有帐户。If you don't yet have an Atlas cluster, create a free M0 cluster.如果您还没有Atlas集群,请创建一个免费的M0集群。To learn more about creating an Atlas cluster, see Create a Cluster.要了解有关创建Atlas集群的更多信息,请参阅创建集群。Note
If you are working with an existing cluster, you must have如果您使用的是现有集群,则必须具有投影数据访问管理员或更高级别的Atlas项目访问权限。Project Data Access Adminor higher access to your Atlas project.If you create a new cluster, you have the necessary permissions by default.如果创建新集群,默认情况下您具有必要的权限。You can create only one每个项目只能创建一个M0Free cluster per project.M0免费集群。In the left sidebar, click Overview. Choose your cluster and click Connect.在左侧边栏中,单击概述。选择集群,然后单击“连接”。
Get mongosh connection details.获取mongosh连接详细信息。
Under Access your data through tools, click Shell.在“通过工具访问数据”下,单击“Shell”。If you haven't already, follow the steps provided to download and install如果您还没有,请按照提供的步骤下载并安装mongosh.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连接到自我管理或Atlas部署。例如:
mongosh "mongodb+srv://my-test-cluster.1twap.mongodb.net/" --apiVersion 1
--username <user>Create a new database.创建新数据库。
use timeseries
This creates and switches to an empty "timeseries" database.这将创建并切换到一个空的“时间序列”数据库。
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.date字段存储时间数据,ticker字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity:timeseries: {
timeField: "date",
metaField: "ticker",
granularity: "seconds"
}Create the collection using the使用db.createCollection()method:db.createCollection()方法创建集合:db.createCollection(
"stocks",
{
timeseries: {
timeField: "date",
metaField: "ticker",
granularity: "seconds"
}
})This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Run the 运行db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法,将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
db.stocks.find( { ticker: "MDB" } )
To query the 要在timeField for a time span:timeField中查询时间跨度,请执行以下操作:
db.stocks.find({ date : {
$gte : ISODate("2021-12-18T15:50:00.000Z"),
$lte : ISODate("2021-12-18T15:56:00.000Z")}
});Atlas(local)
Install local deployment dependencies.安装本地部署依赖项。
For detailed instructions, see Prerequisites.有关详细说明,请参阅先决条件。
Install the Atlas CLI.安装Atlas CLI。If you use Homebrew, you can run the following command in your terminal:如果您使用Homebrew,您可以在终端中运行以下命令:brew install mongodb-atlas-cliFor installation instructions on other operating systems, see Install the Atlas CLI有关其他操作系统上的安装说明,请参阅安装Atlas CLI-
Docker requires a network connection for pulling and caching MongoDB images.Docker需要网络连接来拉取和缓存MongoDB映像。For MacOS or Windows, install Docker Desktop v4.31+.对于MacOS或Windows,请安装Docker Desktop v4.31+。For Linux, install Docker Engine v27.0+.对于Linux,请安装Docker Engine v27.0+。For RHEL, you can also use Podman v5.0+.对于RHEL,您还可以使用Podman v5.0+。
Set up your local Atlas deployment.设置本地Atlas部署。
If you don't have an existing Atlas account, run如果您没有现有的Atlas帐户,请在终端中运行“Atlas设置”或创建新帐户。atlas setupin your terminal or create a new account.Run运行“atlas部署设置程序”,并按照提示创建本地部署。当系统提示连接到部署时,选择“跳过”。atlas deployments setupand 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.有关详细说明,请参阅创建本地Atlas部署。
Install mongosh.安装mongosh。
Go to the 转到mongosh page and click Download mongosh. Check that the platform matches your system and click Download.mongosh页面并单击下载mongosh。检查平台是否与系统匹配,然后单击“下载”。
Open a new terminal window and connect to your deployment.打开一个新的终端窗口并连接到部署。
Use 使用mongosh to connect to your self-managed or Atlas deployment. For example:mongosh连接到自我管理或Atlas部署。例如:
mongosh "mongodb+srv://my-test-cluster.1twap.mongodb.net/" --apiVersion 1
--username <user>Create a new database.创建新数据库。
use timeseries
This creates and switches to an empty "timeseries" database.这将创建并切换到一个空的“时间序列”数据库。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity:timeseries: {
timeField: "date",
metaField: "ticker",
granularity: "seconds"
}Create the collection using the使用db.createCollection()method:db.createCollection()方法创建集合:db.createCollection(
"stocks",
{
timeseries: {
timeField: "date",
metaField: "ticker",
granularity: "seconds"
}
})This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Run the 运行db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法,将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
db.stocks.find( { ticker: "MDB" } )
To query the 要在timeField for a time span:timeField中查询时间跨度,请执行以下操作:
db.stocks.find({ date : {
$gte : ISODate("2021-12-18T15:50:00.000Z"),
$lte : ISODate("2021-12-18T15:56:00.000Z")}
});Self-Managed(on-Premises)
Install MongoDB and local deployment dependencies.安装MongoDB和本地部署依赖项。
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.如果您正在运行自我管理部署,请按照MongoDB版本、版本和平台的安装说明进行操作。
Install mongosh.安装mongosh。
Go to the 转到mongosh page and click Download mongosh. Check that the platform matches your system and click Download.mongosh页面并单击“下载mongosh”。检查平台是否与系统匹配,然后单击“下载”。
Open a new terminal window and connect to your deployment.打开一个新的终端窗口并连接到部署。
Use 使用mongosh to connect to your self-managed or Atlas deployment. For example:mongosh连接到自我管理或Atlas部署。例如:
mongosh "mongodb+srv://my-test-cluster.1twap.mongodb.net/" --apiVersion 1
--username <user>Create a new database.创建新数据库。
use timeseries
This creates and switches to an empty "timeseries" database.这将创建并切换到一个空的“时间序列”数据库。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity: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.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Run the 运行db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法,将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
db.stocks.find( { ticker: "MDB" } )
To query the 要在timeField for a time span:timeField中查询时间跨度,请执行以下操作:
db.stocks.find({ date : {
$gte : ISODate("2021-12-18T15:50:00.000Z"),
$lte : ISODate("2021-12-18T15:56:00.000Z")}
});Node.js
Atlas(Cloud)
Set up your Atlas cluster.设置Atlas集群。
Create a free Atlas account or sign in to an existing account.创建一个免费的Atlas帐户或登录现有帐户。If you don't yet have an Atlas cluster, create a free M0 cluster.如果您还没有Atlas集群,请创建一个免费的M0集群。To learn more about creating an Atlas cluster, see Create a Cluster.要了解有关创建Atlas集群的更多信息,请参阅创建集群。Note
If you are working with an existing cluster, you must have如果您使用的是现有集群,则必须具有投影数据访问管理员或更高级别的Atlas项目访问权限。Project Data Access Adminor higher access to your Atlas project.If you create a new cluster, you have the necessary permissions by default.如果创建新集群,默认情况下您具有必要的权限。You can create only one每个项目只能创建一个M0Free cluster per project.M0Free集群。In the left sidebar, click Overview. Choose your cluster and click Connect.在左侧边栏中,单击概述。选择集群,然后单击连接。
Get Node.js Driver connection details.获取Node.js驱动程序连接详细信息。
Under Connect to your application, click Driver. Select Node.js.在“连接到应用程序”下,单击“驱动程序”。选择Node.js。If you haven't already, follow the steps provided to download and install the Node.js Driver.如果您还没有,请按照提供的步骤下载并安装Node.js驱动程序。Copy your connection string and click Done.复制连接字符串,然后单击“完成”。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到一个新的.jsfile..js文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到// start example code here and // end example code here comments.// start example code here和// end example code here注释之间。
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 a new database.创建新数据库。
const timeSeriesDB = client.db('timeseries');
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
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.date字段存储时间数据,股票代码字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity:const options = {
timeseries: {
timeField: 'date',
metaField: 'ticker',
granularity: 'seconds',
},
};Create the collection using the使用db.createCollection()method:db.createCollection()方法创建集合:const stocks = await timeSeriesDB.createCollection('stocks', options);This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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:timeField中查询时间跨度,请执行以下操作:
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
}
Atlas(local)
Install local deployment dependencies.安装本地部署依赖项。
For detailed instructions, see Prerequisites.有关详细说明,请参阅先决条件。
Install the Atlas CLI.安装Atlas CLI。If you use Homebrew, you can run the following command in your terminal:如果您使用Homebrew,您可以在终端中运行以下命令:brew install mongodb-atlas-cliFor installation instructions on other operating systems, see Install the Atlas CLI有关其他操作系统上的安装说明,请参阅安装Atlas CLI-
Docker requires a network connection for pulling and caching MongoDB images.Docker需要网络连接来拉取和缓存MongoDB映像。For MacOS or Windows, install Docker Desktop v4.31+.对于MacOS或Windows,请安装Docker Desktop v4.31+。For Linux, install Docker Engine v27.0+.对于Linux,请安装Docker Engine v27.0+。For RHEL, you can also use Podman v5.0+.对于RHEL,您还可以使用Podman v5.0+。
Set up your local Atlas deployment.设置本地Atlas部署。
If you don't have an existing Atlas account, run如果您没有现有的Atlas帐户,请在终端中运行“Atlas设置”或创建新帐户。atlas setupin your terminal or create a new account.Run运行atlas部署设置程序,并按照提示创建本地部署。当系统提示连接到部署时,选择“跳过”。atlas deployments setupand 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.有关详细说明,请参阅创建本地Atlas部署。
Install the Node.js Driver.安装Node.js驱动程序。
Follow the directions on the Node.js Get Started page to create a new project directory and install driver dependencies.按照Node.js快速入门页面上的说明创建新的项目目录并安装驱动程序依赖项。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到一个新的.jsfile..js文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到// start example code here and // end example code here comments.// start example code here和// end example code here注释之间。
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 a new database.创建新数据库。
const timeSeriesDB = client.db('timeseries');
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity:const options = {
timeseries: {
timeField: 'date',
metaField: 'ticker',
granularity: 'seconds',
},
};Create the collection using the使用db.createCollection()method:db.createCollection()方法创建集合:const stocks = await timeSeriesDB.createCollection('stocks', options);This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insertMany() method to add the following sample documents to the collection:db.collection.insertMany()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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:timeField中查询时间跨度,请执行以下操作:
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
}
Self-Managed(on-Premises)
Install MongoDB and local deployment dependencies.安装MongoDB和本地部署依赖项。
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.如果您正在运行自我管理部署,请按照MongoDB版本、版本和平台的安装说明进行操作。
Install the Node.js Driver.安装Node.js驱动程序。
Follow the directions on the Node.js Get Started page to create a new project directory and install driver dependencies.按照Node.js快速入门页面上的说明创建新的项目目录并安装驱动程序依赖项。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到一个新的.jsfile..js文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到// start example code here and // end example code here comments.// start example code here和// end example code here注释之间。
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 a new database.创建新数据库。
const timeSeriesDB = client.db('timeseries');
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
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.date字段存储时间数据,ticker字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity:const options = {
timeseries: {
timeField: 'date',
metaField: 'ticker',
granularity: 'seconds',
},
};Create the collection using the使用db.createCollection()method:db.createCollection()方法创建集合: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:db.collection.insertMany()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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:timeField中查询时间跨度,请执行以下操作:
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
}
Python
Atlas(Cloud)
Set up your Atlas cluster.设置Atlas集群。
Create a free Atlas account or sign in to an existing account.创建一个免费的Atlas帐户或登录现有帐户。If you don't yet have an Atlas cluster, create a free M0 cluster.如果您还没有Atlas集群,请创建一个免费的M0集群。To learn more about creating an Atlas cluster, see Create a Cluster.要了解有关创建Atlas集群的更多信息,请参阅创建集群。Note
If you are working with an existing cluster, you must have如果您使用的是现有集群,则必须具有投影数据访问管理员或更高级别的Atlas项目访问权限。Project Data Access Adminor higher access to your Atlas project.If you create a new cluster, you have the necessary permissions by default.如果创建新集群,默认情况下您具有必要的权限。You can create only one每个项目只能创建一个M0Free cluster per project.M0免费集群。In the left sidebar, click Overview. Choose your cluster and click Connect.在左侧边栏中,单击概述。选择集群,然后单击“连接”。
Get PyMongo connection details.获取PyMongo连接详细信息。
Under Connect to your application, click Driver. Select Python.在“连接到应用程序”下,单击“驱动程序”。选择Python。If you haven't already, follow the steps provided to download and install the PyMongo Driver.如果您还没有,请按照提供的步骤下载并安装PyMongo驱动程序。Copy your connection string and click Done.复制连接字符串,然后单击“完成”。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到新的.pyfile..py文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到# start example code here and # end example code here comments.// start example code here和// end example code here注释之间。
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 a new database.创建新数据库。
timeseries_db = client["timeseries"]
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity:time_series_options = {
"timeField": "date",
"metaField": "ticker",
"granularity": "seconds",
}Create the collection using the使用db.create_collection()method:db.create_collection()方法创建集合:timeseries_db.create_collection("stocks", timeseries=time_series_options)This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insert_many() method to add the following sample documents to the collection:db.collection.insert_many()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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中查询时间跨度,请执行以下操作:
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}
Atlas(local)
Install local deployment dependencies.安装本地部署依赖项。
For detailed instructions, see Prerequisites.有关详细说明,请参阅先决条件。
Install the Atlas CLI.安装Atlas CLI。If you use Homebrew, you can run the following command in your terminal:如果您使用Homebrew,您可以在终端中运行以下命令:brew install mongodb-atlas-cliFor installation instructions on other operating systems, see Install the Atlas CLI有关其他操作系统上的安装说明,请参阅安装Atlas CLI-
Docker requires a network connection for pulling and caching MongoDB images.Docker需要网络连接来拉取和缓存MongoDB映像。For MacOS or Windows, install Docker Desktop v4.31+.对于MacOS或Windows,请安装Docker Desktop v4.31+。For Linux, install Docker Engine v27.0+.对于Linux,请安装Docker Engine v27.0+。For RHEL, you can also use Podman v5.0+.对于RHEL,您还可以使用Podman v5.0+。
Set up your local Atlas deployment.设置本地Atlas部署。
If you don't have an existing Atlas account, run如果您没有现有的Atlas帐户,请在终端中运行“Atlas设置”或创建新帐户。atlas setupin your terminal or create a new account.Run运行“atlas部署设置程序”,并按照提示创建本地部署。当系统提示连接到部署时,选择“跳过”。atlas deployments setupand 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.有关详细说明,请参阅创建本地Atlas部署。
Install the PyMongo Driver.安装PyMongo驱动程序。
Follow the directions on the PyMongo Get Started page to create a new project directory and install driver dependencies.按照PyMongo快速入门页面上的说明创建新的项目目录并安装驱动程序依赖项。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到新的.pyfile..py文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到# start example code here and # end example code here comments.// start example code here和// end example code here注释之间。
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 a new database.创建新数据库。
timeseries_db = client["timeseries"]
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity:time_series_options = {
"timeField": "date",
"metaField": "ticker",
"granularity": "seconds",
}Create the collection using the使用db.create_collection()method:db.create_collection()方法创建集合:timeseries_db.create_collection("stocks", timeseries=time_series_options)This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insert_many() method to add the following sample documents to the collection:db.collection.insert_many()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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中查询时间跨度,请执行以下操作:
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}
Self-Managed(on-Premises)
Install MongoDB and local deployment dependencies.安装MongoDB和本地部署依赖项。
If you're running a self-managed deployment, follow the installation instructions for your MongoDB version, edition, and platform.如果您正在运行自我管理部署,请按照MongoDB版本、版本和平台的安装说明进行操作。
Install the PyMongo Driver.安装PyMongo驱动程序。
Follow the directions on the PyMongo Get Started page to create a new project directory and install driver dependencies.按照PyMongo快速入门页面上的说明创建新的项目目录并安装驱动程序依赖项。
Copy the template app and connect to your deployment.复制模板应用程序并连接到部署。
Paste the following code into a new将以下代码粘贴到新的.pyfile..py文件中。Replace将"<connection-string>"with your copied connection string."<connection-string>"替换为复制的连接字符串。
As you work with time series code examples, add them between the 当您使用时间序列代码示例时,请将它们添加到# start example code here and # end example code here comments.// start example code here和// end example code here注释之间。
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 a new database.创建新数据库。
timeseries_db = client["timeseries"]
This creates a reference to an empty "timeseries" database.这将创建对空“时间序列”数据库的引用。
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.date字段存储时间数据,ticker(股票代码)字段标识单个股票。
Set the设置timeField,metaField, andgranularity:timeField、metaField和granularity:time_series_options = {
"timeField": "date",
"metaField": "ticker",
"granularity": "seconds",
}Create the collection using the使用db.create_collection()method:db.create_collection()方法创建集合:timeseries_db.create_collection("stocks", timeseries=time_series_options)This creates an empty time series collection named这将创建一个名为stocks.stocks的空时间序列集合。
Add sample documents.添加示例文档。
Use the 使用db.collection.insert_many() method to add the following sample documents to the collection:db.collection.insert_many()方法将以下示例文档添加到集合中:
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.如果您在Atlas上运行MongoDB,可以单击“浏览集合”以查看示例数据。
Query the data.查询数据。
You query a time series collection like any other MongoDB collection. For more information, see About Querying Time Series Data.您可以像查询任何其他MongoDB集合一样查询时间序列集合。有关更多信息,请参阅关于查询时间序列数据。
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.metaField以获取单个时间序列的数据,或者使用timeField上的范围查询来获取给定时间跨度的数据。
To query the 要查询单个时间序列的metaField for a single time series:metaField,请执行以下操作:
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中查询时间跨度,请执行以下操作:
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.stocks时间序列集合。
{
_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.要了解更多关于MongoDB如何在内部存储时间序列数据的信息,请参阅关于时间序列数据。To learn more about custom bucketing parameters in MongoDB 6.3 and later, see Using Custom Bucketing Parameters.要了解更多关于MongoDB 6.3及更高版本中自定义桶参数的信息,请参阅使用自定义桶参数。