summaryrefslogtreecommitdiff
path: root/jstests/aggregation/sources/setWindowFields/avg.js
blob: da5ee8925ce6c13879a0a162d33151a5187ed1a3 (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
/**
 * Test that $avg works as a window function.
 */
(function() {
"use strict";

load("jstests/aggregation/extras/window_function_helpers.js");

const coll = db[jsTestName()];
coll.drop();

// Create a collection of tickers and prices.
const nDocsPerTicker = 10;
seedWithTickerData(coll, nDocsPerTicker);

// Run the suite of partition and bounds tests against the $avg function.
testAccumAgainstGroup(coll, "$avg");

// Test a combination of two different runnning averages.
let results =
    coll.aggregate([
            {
                $setWindowFields: {
                    sortBy: {_id: 1},
                    partitionBy: "$ticker",
                    output: {
                        runningAvg: {$avg: "$price", window: {documents: ["unbounded", "current"]}},
                        runningAvgLead: {$avg: "$price", window: {documents: ["unbounded", 3]}},
                    }
                },
            },
        ])
        .toArray();
for (let index = 0; index < results.length; index++) {
    // First compute the 'runningAvg' with 0 as the upper bound.
    let groupRes = computeAsGroup({
        coll: coll,
        partitionKey: {ticker: results[index].ticker},
        accumSpec: {"$avg": "$price"},
        bounds: ["unbounded", 0],
        indexInPartition: results[index].partIndex,
        defaultValue: null
    });
    assert.eq(groupRes, results[index].runningAvg);

    // Now compute the 'runningAvgLead' with 3 as the upper bound.
    groupRes = computeAsGroup({
        coll: coll,
        partitionKey: {ticker: results[index].ticker},
        accumSpec: {"$avg": "$price"},
        bounds: ["unbounded", 3],
        indexInPartition: results[index].partIndex,
        defaultValue: null
    });
    assert.eq(groupRes, results[index].runningAvgLead);
}
})();