按 unix 时间戳范围分组
Group by range of unix timestamp
我正在尝试对 MongoDB 集合中每分钟 table 的结果进行分组。
我有一个集合,每秒或多或少有一个文档。原型如下:
{
_id: ...
type: "value",
time: 1424421975,
data: number
}
现在我想创建第二个具有相同原型的集合,该原型首先按类型分组,然后按时间(每分钟)分组。
我已经尝试使用 MongoDB 中的 map reduce 进行一些操作,但我无法使其正常工作。
var mapFunction1 = function() {
var firstTimestamp = db.collection.find({type: this.type}).sort({time: 1}).limit(1)[0].time;
var keyValue = Math.floor((this.time - firstTimestamp) / 60) * 60 + firstTimestamp;
emit(this.type + '_' + keyValue, this);
}
var reduceFunction1 = function(key, value) {
return value;
};
db.loadServerScripts();
db.runCommand({
mapreduce: "collection",
map: mapFunction1,
reduce: reduceFunction1,
out: "map_reduce_example",
scope: {db: db}
});
给出错误信息:
{
"errmsg" : "exception: TypeError: Object db.collection has no method 'find' near 'collection.find({type:this.type' (line 2)",
"code" : 16722,
"ok" : 0
}
您可以为此使用聚合管道。诀窍是按使用 arithmetic operators:
计算的分钟进行分组
db.collection.aggregate([
{ "$group" : {
"_id" : {
"type" : "$type",
"minute" : {
"$divide" : [
{ "$subtract" : ["$time", { "$mod" : ["$time", 60] }] },
60
]
}
},
"data" : { "$sum" : "$data" } // assuming you want to add up data for seconds
} }
])
如果要针对分钟之间的不同边界进行调整,请在 $subtract
表达式中向 $time
添加偏移量。如果你想让你的生活更轻松(在这种情况下),请将 time
替换为实际日期类型并使用 $minute
.
我正在尝试对 MongoDB 集合中每分钟 table 的结果进行分组。
我有一个集合,每秒或多或少有一个文档。原型如下:
{
_id: ...
type: "value",
time: 1424421975,
data: number
}
现在我想创建第二个具有相同原型的集合,该原型首先按类型分组,然后按时间(每分钟)分组。
我已经尝试使用 MongoDB 中的 map reduce 进行一些操作,但我无法使其正常工作。
var mapFunction1 = function() {
var firstTimestamp = db.collection.find({type: this.type}).sort({time: 1}).limit(1)[0].time;
var keyValue = Math.floor((this.time - firstTimestamp) / 60) * 60 + firstTimestamp;
emit(this.type + '_' + keyValue, this);
}
var reduceFunction1 = function(key, value) {
return value;
};
db.loadServerScripts();
db.runCommand({
mapreduce: "collection",
map: mapFunction1,
reduce: reduceFunction1,
out: "map_reduce_example",
scope: {db: db}
});
给出错误信息:
{
"errmsg" : "exception: TypeError: Object db.collection has no method 'find' near 'collection.find({type:this.type' (line 2)",
"code" : 16722,
"ok" : 0
}
您可以为此使用聚合管道。诀窍是按使用 arithmetic operators:
计算的分钟进行分组db.collection.aggregate([
{ "$group" : {
"_id" : {
"type" : "$type",
"minute" : {
"$divide" : [
{ "$subtract" : ["$time", { "$mod" : ["$time", 60] }] },
60
]
}
},
"data" : { "$sum" : "$data" } // assuming you want to add up data for seconds
} }
])
如果要针对分钟之间的不同边界进行调整,请在 $subtract
表达式中向 $time
添加偏移量。如果你想让你的生活更轻松(在这种情况下),请将 time
替换为实际日期类型并使用 $minute
.