summaryrefslogtreecommitdiff
path: root/jstests/aggregation/sources/lookup/lookup_sort_limit.js
blob: 3633852615b6074c45ddbb9de1876b809ca4c8d8 (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
/**
 * Test that a $lookup correctly optimizes a foreign pipeline containing a $sort and a $limit. This
 * test is designed to reproduce SERVER-36715.
 *
 * @tags: [assumes_unsharded_collection]
 */
(function() {
    "use strict";

    load("jstests/libs/analyze_plan.js");  // For getAggPlanStages().

    const testDB = db.getSiblingDB("lookup_sort_limit");
    testDB.dropDatabase();

    const localColl = testDB.getCollection("local");
    const fromColl = testDB.getCollection("from");

    const bulk = fromColl.initializeUnorderedBulkOp();
    for (let i = 0; i < 10; i++) {
        bulk.insert({_id: i, foreignField: i});
    }
    assert.commandWorked(bulk.execute());
    assert.commandWorked(localColl.insert({_id: 0}));

    let res = localColl
                  .aggregate([{
                      $lookup: {
                          from: fromColl.getName(),
                          let : {},
                          pipeline: [{$sort: {_id: 1}}, {$limit: 1}],
                          as: "result"
                      }
                  }])
                  .toArray();

    assert.eq({_id: 0, result: [{_id: 0, foreignField: 0}]}, res[0]);

    // Run a similar test except with a sort that cannot be covered with an index scan.
    res = localColl
              .aggregate([{
                  $lookup: {
                      from: fromColl.getName(),
                      let : {},
                      pipeline: [{$sort: {foreignField: -1}}, {$limit: 1}],
                      as: "result"
                  }
              }])
              .toArray();

    assert.eq({_id: 0, result: [{_id: 9, foreignField: 9}]}, res[0]);

}());