MongoDB 聚合框架采样率
MongoDB Aggregation Framework sample rate
我想为我的数据库解决方案尝试 MongoDB,所以我正在试用它。 Aggregation Framework 非常完美,大部分文档都很好地解释了我必须做什么。
我的数据是这样的:
{ "_id" : ObjectId("54e5e79032d4796d1dec195e"),
"timestamp" : ISODate("2015-01-20T10:31:02.082Z"),
"value" : 4089 }
例如,如果我想每秒聚合我的数据,我会这样做:
db.mycollection.aggregate(
{
$match : {
timestamp: {$gte: ISODate("2015-01-21T12:00:00Z"),
$lte: ISODate("2015-01-21T12:01:00Z")}
}
},
{
$group : {
_id : { $second: "$timestamp" },
averageQuantity: { $avg: "$value" },
count: { $sum: 1 }
}
}
);
我的问题是,我必须怎么做才能按 而不是 predefined 的采样率聚合我的数据,例如 $second 或 $minute,但是让我们说 30 秒?
使用我示例中的代码,我想要返回 2 个结果。
提前致谢!
what do I have to do to aggregate my data by a sample rate that's not predefined, like $second or $minute, but let's say by 30 seconds?
聚合管道中的大量数学运算。例如,如果你想花费一天的时间并按 30 秒的间隔分组,你需要使用 timestamp
并计算它代表一天的秒数,然后将其转换为四舍五入的#每天间隔 30 秒,然后分组。
db.mycollection.aggregate([
{ "$project" : {
"secs" : {
"$add" : [
{ "$multiply" : [{ "$hour" : "$timestamp"}, 60, 60] },
{ "$multiply" : [{ "$minute" : "$timestamp"}, 60] }
{ "$second" : "$timestamp"}
]
}
"value" : 1
} },
{ "$group" : {
"_id" : {
"$divide" : [
{ "$subtract" : [
"$secs",
{ "$mod" : ["$secs", 30] }
] },
30
]
},
"value" : { "$sum" : "$value" }
} }
])
我想为我的数据库解决方案尝试 MongoDB,所以我正在试用它。 Aggregation Framework 非常完美,大部分文档都很好地解释了我必须做什么。
我的数据是这样的:
{ "_id" : ObjectId("54e5e79032d4796d1dec195e"),
"timestamp" : ISODate("2015-01-20T10:31:02.082Z"),
"value" : 4089 }
例如,如果我想每秒聚合我的数据,我会这样做:
db.mycollection.aggregate(
{
$match : {
timestamp: {$gte: ISODate("2015-01-21T12:00:00Z"),
$lte: ISODate("2015-01-21T12:01:00Z")}
}
},
{
$group : {
_id : { $second: "$timestamp" },
averageQuantity: { $avg: "$value" },
count: { $sum: 1 }
}
}
);
我的问题是,我必须怎么做才能按 而不是 predefined 的采样率聚合我的数据,例如 $second 或 $minute,但是让我们说 30 秒?
使用我示例中的代码,我想要返回 2 个结果。
提前致谢!
what do I have to do to aggregate my data by a sample rate that's not predefined, like $second or $minute, but let's say by 30 seconds?
聚合管道中的大量数学运算。例如,如果你想花费一天的时间并按 30 秒的间隔分组,你需要使用 timestamp
并计算它代表一天的秒数,然后将其转换为四舍五入的#每天间隔 30 秒,然后分组。
db.mycollection.aggregate([
{ "$project" : {
"secs" : {
"$add" : [
{ "$multiply" : [{ "$hour" : "$timestamp"}, 60, 60] },
{ "$multiply" : [{ "$minute" : "$timestamp"}, 60] }
{ "$second" : "$timestamp"}
]
}
"value" : 1
} },
{ "$group" : {
"_id" : {
"$divide" : [
{ "$subtract" : [
"$secs",
{ "$mod" : ["$secs", 30] }
] },
30
]
},
"value" : { "$sum" : "$value" }
} }
])