这是有可能的。请记住,Pandas 是一个专门为此类任务构建的库,并且非常擅长,而 MongoDB 则旨在成为一个数据库。但是,如果忽略您可能需要使用插值,以下内容很可能会满足您的需求:
假设您有以下数据存储在名为的 MongoDB 集合中devices
/* 0 */
{
"_id" : ObjectId("543fc08ccf1e8c06c0288802"),
"t" : ISODate("2014-10-20T14:56:44.097+02:00"),
"a" : "192.168.0.16",
"i" : 0,
"o" : 32
}
/* 1 */
{
"_id" : ObjectId("543fc08ccf1e8c06c0288803"),
"t" : ISODate("2014-10-20T14:56:59.107+02:00"),
"a" : "192.168.0.16",
"i" : 14243,
"o" : 8430
}
and so on...
在本例中,大约每 15 秒采样一次,但也可以不规则。如果您想在某一天将其重新采样到 5 分钟边界,那么您应该执行以下操作:
var low = ISODate("2014-10-23T00:00:00.000+02:00")
var high = ISODate("2014-10-24T00:00:00.000+02:00")
var interval = 5*60*1000;
db.devices.aggregate([
{$match: {t:{$gte: low, $lt: high}, a:"192.168.0.16"}},
{$group: {
_id:{
$subtract: ["$t", {
$mod: [{
$subtract: ["$t", low]
}, interval]
}]
},
total: {$sum: 1},
incoming: {$sum: "$i"},
outgoing: {$sum: "$o"},
}
},
{
$project: {
total: true,
incoming: true,
outgoing: true,
incoming_avg: {$divide: ["$incoming", "$total"]},
outgoing_avg: {$divide: ["$outgoing", "$total"]},
},
},
{$sort: {_id : 1}}
])
这会导致类似这样的结果
{
"result" : [
{
"_id" : ISODate("2014-10-23T07:25:00.000+02:00"),
"total" : 8,
"incoming" : 11039108,
"outgoing" : 404983,
"incoming_avg" : 1379888.5,
"outgoing_avg" : 50622.875
},
{
"_id" : ISODate("2014-10-23T07:30:00.000+02:00"),
"total" : 19,
"incoming" : 187241,
"outgoing" : 239912,
"incoming_avg" : 9854.78947368421,
"outgoing_avg" : 12626.94736842105
},
{
"_id" : ISODate("2014-10-23T07:35:00.000+02:00"),
"total" : 17,
"incoming" : 22420099,
"outgoing" : 1018766,
"incoming_avg" : 1318829.352941176,
"outgoing_avg" : 59927.41176470588
},
...
如果您想丢弃总传入量,则只需在 $project 阶段保留该行即可。传入_average只是一个如何计算平均值的示例,以防您存储的数据类似于rrdtool命名的仪表(温度、CPU、传感器数据)。如果您仅在该时间间隔内聚合的总和(即传入和传出字段)之后,那么您可以将整个 $project 阶段排除在外。它仅用于计算时间间隔的平均值。
See Mongo 将 ISODate 聚合为 45 分钟的块 https://stackoverflow.com/questions/26411949/mongo-aggregation-of-isodate-into-45-minute-chunks