summaryrefslogtreecommitdiff
path: root/jstests/aggregation/sources/facet/inner_lookup.js
blob: 0852f82086962a13bcaf1a83a63be6577e9fd234 (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
// Cannot implicitly shard accessed collections because unsupported use of sharded collection
// for target collection of $lookup and $graphLookup.
// @tags: [assumes_unsharded_collection]

/**
 * Tests that using a $lookup stage inside of a $facet stage will yield the same results as using
 * the $lookup stage outside of the $facet stage.
 */
(function() {
"use strict";

var local = db.facetLookupLocal;
var foreign = db.facetLookupForeign;

local.drop();
assert.writeOK(local.insert({_id: 0}));
assert.writeOK(local.insert({_id: 1}));

foreign.drop();
assert.writeOK(foreign.insert({_id: 0, foreignKey: 0}));
assert.writeOK(foreign.insert({_id: 1, foreignKey: 1}));
assert.writeOK(foreign.insert({_id: 2, foreignKey: 2}));

function runTest(lookupStage) {
    const lookupResults = local.aggregate([lookupStage]).toArray();
    const facetedLookupResults = local.aggregate([{$facet: {nested: [lookupStage]}}]).toArray();
    assert.eq(facetedLookupResults, [{nested: lookupResults}]);

    const lookupResultsUnwound = local.aggregate([lookupStage, {$unwind: "$joined"}]).toArray();
    const facetedLookupResultsUnwound =
        local.aggregate([{$facet: {nested: [lookupStage, {$unwind: "$joined"}]}}]).toArray();
    assert.eq(facetedLookupResultsUnwound, [{nested: lookupResultsUnwound}]);
}

runTest({
    $lookup: {from: foreign.getName(), localField: "_id", foreignField: "foreignKey", as: "joined"}
});

runTest({
        $lookup: {
            from: foreign.getName(),
            let : {id1: "$_id"},
            pipeline: [
                {$match: {$expr: {$eq: ["$$id1", "$foreignKey"]}}},
                {
                  $lookup: {
                      from: foreign.getName(),
                      let : {id2: "$_id"},
                      pipeline: [{$match: {$expr: {$eq: ["$$id2", "$foreignKey"]}}}],
                      as: "joined2"
                  }
                },
                {$unwind: "$joined2"}
            ],
            as: "joined"
        }
    });
}());