如何使用MongoDB聚合器按最大值和最小值之间的统一数据间隔进行分组



假设我有一大堆数据,这些数据为特定字段生成了一系列整数值。。。我希望看到那些按发生间隔分组进行排名,也许是因为我正在聚类。。。像这样:

[{
_id: {
response_time: "3-4"
},
count: 234,
countries: ['US', 'Canada', 'UK']
}, {
_id: {
response_time: "4-5"
},
count: 452,
countries: ['US', 'Canada', 'UK', 'Poland']
}, ...
}]

如何编写一种快速而肮脏的方法来a)使用MongoDB聚合器在B)最小和最大范围内按等距间隔对收集数据进行分组?

为了快速为MongoDB聚合器制定条件分组语法,我们首先采用以下模式,根据MongoDB语法:

$cond: [
{ <conditional> }, // test the conditional
<truthy_value>,  // assign if true
$cond: [ // evaluate if false
{ <conditional> },
<truthy_value>,
...  // and so forth
]
]

为了做到这一点,不必在深度嵌套的条件中写出最后一个间隔,我们可以使用这种方便的递归算法(当然是在shell脚本或node.js脚本中导入的算法):

$condIntervalBuilder = function (field, interval, min, max) {
if (min < max - 1) {
var cond = [
{ '$and': [{ $gt:[field, min] }, { $lte: [field, min + interval] }] },
[min, '-', (min + interval)].join('')
];
if ((min + interval) > max) {
cond.push(ag.$condIntervalBuilder(field, (max - min), min, max));
} else {
min += interval;
cond.push(ag.$condIntervalBuilder(field, interval, min, max));
}
} else if (min >= max - 1 ) {
var cond = [
{ $gt: [field, max] },
[ max, '<' ].join(''), // Accounts for all outside the range
[ min, '<' ].join('') // Lesser upper bound
];
}
return { $cond: cond };
};

然后,我们可以在线调用它,或者将它分配给我们在分析中其他地方使用的变量。

最新更新