summaryrefslogtreecommitdiff
path: root/jstests/aggregation/bugs/ifnull.js
blob: 8967ffe7ab754fe15a56d2c8a21943655f7172e0 (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
// $ifNull returns the result of the first expression if not null or undefined, otherwise of the
// second expression.
load('jstests/aggregation/extras/utils.js');

t = db.jstests_aggregation_ifnull;
t.drop();

t.save({});

function assertError(expectedErrorCode, ifNullSpec) {
    assertErrorCode(t, {$project: {a: {$ifNull: ifNullSpec}}}, expectedErrorCode);
}

function assertResult(expectedResult, arg0, arg1) {
    var res = t.aggregate({$project: {a: {$ifNull: [arg0, arg1]}}}).toArray()[0];
    assert.eq(expectedResult, res.a);
}

// Wrong number of args.
assertError(16020, []);
assertError(16020, [1]);
assertError(16020, [null]);
assertError(16020, [1, 1, 1]);
assertError(16020, [1, 1, null]);
assertError(16020, [1, 1, undefined]);

// First arg non null.
assertResult(1, 1, 2);
assertResult(2, 2, 1);
assertResult(false, false, 1);
assertResult('', '', 1);
assertResult([], [], 1);
assertResult({}, {}, 1);
assertResult(1, 1, null);
assertResult(2, 2, undefined);

// First arg null.
assertResult(2, null, 2);
assertResult(1, null, 1);
assertResult(null, null, null);
assertResult(undefined, null, undefined);

// First arg undefined.
assertResult(2, undefined, 2);
assertResult(1, undefined, 1);
assertResult(null, undefined, null);
assertResult(undefined, undefined, undefined);

// Computed expression.
assertResult(3, {$add: [1, 2]}, 5);
assertResult(20, '$missingField', {$multiply: [4, 5]});

// Divide/mod by 0.
assertError(16608, [{$divide: [1, 0]}, 0]);
assertError(16610, [{$mod: [1, 0]}, 0]);

// Nested.
t.drop();
t.save({d: 'foo'});
assertResult('foo', '$a', {$ifNull: ['$b', {$ifNull: ['$c', '$d']}]});
t.update({}, {$set: {b: 'bar'}});
assertResult('bar', '$a', {$ifNull: ['$b', {$ifNull: ['$c', '$d']}]});