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
|
// test short-circuiting of $and and $or in
// $project stages to a $const boolean
var t = db.jstests_aggregation_server6192;
t.drop();
t.save( {x: true} );
function assertOptimized(pipeline, v) {
var explained = t.runCommand("aggregate", {
pipeline: pipeline,
explain: true
});
printjson({input: pipeline, output: explained});
assert("stages" in explained);
assert("$project" in explained.stages[1]);
var projectStage = explained.stages[1]["$project"];
assert.eq(projectStage.a["$const"], v, "ensure short-circuiting worked");
}
function assertNotOptimized(pipeline) {
var explained = t.runCommand("aggregate", {
pipeline: pipeline,
explain: true
});
printjson({input: pipeline, output: explained});
assert("stages" in explained);
assert("$project" in explained.stages[1]);
var projectStage = explained.stages[1]["$project"];
assert(!("$const" in projectStage.a), "ensure no short-circuiting");
}
// short-circuiting for $and
assertOptimized([ {$project: {a: {$and: [0, '$x']}}} ], false);
assertOptimized([ {$project: {a: {$and: [0, 1, '$x']}}} ], false);
assertOptimized([ {$project: {a: {$and: [0, 1, '', '$x']}}} ], false);
assertOptimized([ {$project: {a: {$and: [1, 0, '$x']}}} ], false);
assertOptimized([ {$project: {a: {$and: [1, '', 0, '$x']}}} ], false);
assertOptimized([ {$project: {a: {$and: [1, 1, 0, 1]}}} ], false);
// short-circuiting for $or
assertOptimized([ {$project: {a: {$or: [1, '$x']}}} ], true);
assertOptimized([ {$project: {a: {$or: [1, 0, '$x']}}} ], true);
assertOptimized([ {$project: {a: {$or: [1, '', '$x']}}} ], true);
assertOptimized([ {$project: {a: {$or: [0, 1, '$x']}}} ], true);
assertOptimized([ {$project: {a: {$or: ['', 0, 1, '$x']}}} ], true);
assertOptimized([ {$project: {a: {$or: [0, 0, 0, 1]}}} ], true);
// examples that should not short-circuit
assertNotOptimized([ {$project: {a: {$and: [1, '$x']}}} ]);
assertNotOptimized([ {$project: {a: {$or: [0, '$x']}}} ]);
assertNotOptimized([ {$project: {a: {$and: ['$x', '$x']}}} ]);
assertNotOptimized([ {$project: {a: {$or: ['$x', '$x']}}} ]);
assertNotOptimized([ {$project: {a: {$and: ['$x']}}} ]);
assertNotOptimized([ {$project: {a: {$or: ['$x']}}} ]);
|