假设我有一大堆数据,这些数据为特定字段产生了一系列整数值……我希望看到它们按照发生间隔的分组进行排序,可能是因为我是clustering...like,所以:
[{
_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)上的等间距间隔对收集数据分组最小和最大范围?
发布于 2016-05-28 15:04:08
好的,为了快速形成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 };
};
然后,我们可以内联调用它,或者将它赋值给我们在分析中其他地方使用的变量。
https://stackoverflow.com/questions/37496209
复制相似问题