好吧,为了快速为 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 };
};
然后,我们可以在线调用它或将其分配给我们在分析中其他地方使用的变量。