summaryrefslogtreecommitdiff
path: root/jstests/aggregation/expressions/n_expressions.js
blob: 60ea494b81d5ed27e077e3c1a2daa8486c92f7d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
 * Tests the 'n' family of accumulators implemented as expressions.
 */
(function() {
'use strict';

const coll = db[jsTestName()];
const doc = {
    a: [1, 2, 3, 5, 7, 9],
    n: 4,
    diff: 2
};

const isExactTopNEnabled = db.adminCommand({getParameter: 1, featureFlagExactTopNAccumulator: 1})
                               .featureFlagExactTopNAccumulator.value;

if (!isExactTopNEnabled) {
    // Verify that $minN/$maxN cannot be used if the feature flag is set to false and ignore the
    // rest of the test.
    assert.commandFailedWithCode(
        coll.runCommand(
            "aggregate",
            {pipeline: [{$project: {output: {'$minN': {n: 3, input: [3, 1, 2, 3]}}}}], cursor: {}}),
        31325);
    return;
}

coll.drop();
assert.commandWorked(coll.insert(doc));

function testExpr(expression, expected) {
    assert.eq(coll.aggregate([{$project: {_id: 0, output: expression}}]).toArray()[0].output,
              expected);
}

let args = {n: 3, input: [5, 4, 3, 2, 1]};
testExpr({$minN: args}, [1, 2, 3]);
testExpr({$maxN: args}, [5, 4, 3]);
testExpr({$firstN: args}, [5, 4, 3]);
testExpr({$lastN: args}, [3, 2, 1]);
args = {
    n: 3,
    input: [null, 2, null, 1]
};
testExpr({$minN: args}, [1, 2]);
testExpr({$maxN: args}, [2, 1]);
testExpr({$firstN: args}, [null, 2, null]);
testExpr({$lastN: args}, [2, null, 1]);
args = {
    n: 3,
    input: "$a"
};
testExpr({$minN: args}, [1, 2, 3]);
testExpr({$maxN: args}, [9, 7, 5]);
testExpr({$firstN: args}, [1, 2, 3]);
testExpr({$lastN: args}, [5, 7, 9]);
args = {
    n: "$n",
    input: "$a"
};
testExpr({$minN: args}, [1, 2, 3, 5]);
testExpr({$maxN: args}, [9, 7, 5, 3]);
testExpr({$firstN: args}, [1, 2, 3, 5]);
testExpr({$lastN: args}, [3, 5, 7, 9]);
args = {
    n: {$subtract: ["$n", "$diff"]},
    input: [3, 4, 5]
};
testExpr({$minN: args}, [3, 4]);
testExpr({$maxN: args}, [5, 4]);
testExpr({$firstN: args}, [3, 4]);
testExpr({$lastN: args}, [4, 5]);
})();