MongoDB 中时间序列数据的聚合
Aggregation over timeseries data in MongoDB
我在 MongoDB 中管理我的 PC 时间序列数据,格式为:
- 我正在为每个服务器创建一个小时的文档。
- 然后我尝试以如下所示的格式存储每分钟的 cpuMetric 数据。
问题是我不知道如何在聚合中使用 cpuMetric 中的数据。
更具体地说,我想从该文档中获取最近 10 分钟的数据。
{ "_id" : "192.168.xxx.xxx1440yyy000",
"time" : ISODate("2015-yy-xxT05:30:00Z"),
"ip" : "192.168.xxx.xxx",
"serverId" : "abc",
"cpuMetric" : {
"0" : { "usage" : 25.99, "process" : 123, "cores" : 4, "speed" : 2394, "uptime" : 45839 },
"1" : { "speed" : 2394, "uptime" : 45899, "usage" : 26.003333333333334, "process" : 121, "cores" : 4 },
.
.
.
"58" : { "usage" : 26.093333333333334, "process" : 119, "cores" : 4, "speed" : 2394, "uptime" : 45959 },
"59" : { "usage" : 26.73, "process" : 119, "cores" : 4, "speed" : 2394, "uptime" : 46019 }
}
}
提前致谢!!
如果为时不晚,最好更改数据模式。对于这个,您不能使用索引,因为您使用的值基本上是分钟作为字段名称。因此,更好的方法是将分钟数据保存在数组中,并将数据值用作分钟。然后您可以索引 cpuMetric.minute
字段并轻松对数据进行排序。
{ "_id" : "192.168.xxx.xxx1440yyy000",
"time" : ISODate("2015-yy-xxT05:30:00Z"),
"ip" : "192.168.xxx.xxx",
"serverId" : "abc",
"cpuMetric: [{minute: ISODate("2015-yy-xxT05:30:00Z")", { "usage" : 25.99, "process" : 123, "cores" : 4, "speed" : 2394, "uptime" : 45839 }}, {minute: ISODate("2015-yy-xxT05:31:00Z"), { "speed" : 2394, "uptime" : 45899, "usage" : 26.003333333333334, "process" : 121, "cores" : 4 }}, ...]
之后,您可以查询数据并在字段 cpuMetric.minute
上对数据进行排序。
db.pcmetrics.find(
{ cpuMetric: { $elemMatch: {minute: {$gte: 10MinutesAgoInDateFormat} } } }
)
我在 MongoDB 中管理我的 PC 时间序列数据,格式为:
- 我正在为每个服务器创建一个小时的文档。
- 然后我尝试以如下所示的格式存储每分钟的 cpuMetric 数据。
问题是我不知道如何在聚合中使用 cpuMetric 中的数据。
更具体地说,我想从该文档中获取最近 10 分钟的数据。
{ "_id" : "192.168.xxx.xxx1440yyy000",
"time" : ISODate("2015-yy-xxT05:30:00Z"),
"ip" : "192.168.xxx.xxx",
"serverId" : "abc",
"cpuMetric" : {
"0" : { "usage" : 25.99, "process" : 123, "cores" : 4, "speed" : 2394, "uptime" : 45839 },
"1" : { "speed" : 2394, "uptime" : 45899, "usage" : 26.003333333333334, "process" : 121, "cores" : 4 },
.
.
.
"58" : { "usage" : 26.093333333333334, "process" : 119, "cores" : 4, "speed" : 2394, "uptime" : 45959 },
"59" : { "usage" : 26.73, "process" : 119, "cores" : 4, "speed" : 2394, "uptime" : 46019 }
}
}
提前致谢!!
如果为时不晚,最好更改数据模式。对于这个,您不能使用索引,因为您使用的值基本上是分钟作为字段名称。因此,更好的方法是将分钟数据保存在数组中,并将数据值用作分钟。然后您可以索引 cpuMetric.minute
字段并轻松对数据进行排序。
{ "_id" : "192.168.xxx.xxx1440yyy000",
"time" : ISODate("2015-yy-xxT05:30:00Z"),
"ip" : "192.168.xxx.xxx",
"serverId" : "abc",
"cpuMetric: [{minute: ISODate("2015-yy-xxT05:30:00Z")", { "usage" : 25.99, "process" : 123, "cores" : 4, "speed" : 2394, "uptime" : 45839 }}, {minute: ISODate("2015-yy-xxT05:31:00Z"), { "speed" : 2394, "uptime" : 45899, "usage" : 26.003333333333334, "process" : 121, "cores" : 4 }}, ...]
之后,您可以查询数据并在字段 cpuMetric.minute
上对数据进行排序。
db.pcmetrics.find(
{ cpuMetric: { $elemMatch: {minute: {$gte: 10MinutesAgoInDateFormat} } } }
)