summaryrefslogtreecommitdiff
path: root/jstests/core/query/mr/mr_use_this_object.js
blob: 524cf6436605679bcb9de743b3350067a0212aac (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
63
64
65
66
67
68
69
70
71
72
73
74
75
// Tests that the map function can access state of the 'this' object using both the '.x' and ["x"]
// syntax.
// The test runs commands that are not allowed with security token: mapReduce.
// @tags: [
//   not_allowed_with_security_token,
//   # mapReduce does not support afterClusterTime.
//   does_not_support_causal_consistency,
//   does_not_support_stepdowns,
//   uses_map_reduce_with_temp_collections,
//   # Uses mapReduce command.
//   requires_scripting,
// ]
(function() {
"use strict";

load("jstests/aggregation/extras/utils.js");  // For resultsEq.

const coll = db.mr_use_this_object;
coll.drop();
const outputColl = db.mr_use_this_object_out;
outputColl.drop();

assert.commandWorked(coll.insert([
    {partner: 1, visits: 9},
    {partner: 2, visits: 9},
    {partner: 1, visits: 11},
    {partner: 1, visits: 30},
    {partner: 2, visits: 41},
    {partner: 2, visits: 41}
]));

let mapper = function() {
    emit(this.partner, {stats: [this.visits]});
};

const reducer = function(k, v) {
    let stats = [];
    let total = 0;
    for (let i = 0; i < v.length; i++) {
        for (let j in v[i].stats) {
            stats.push(v[i].stats[j]);
            total += v[i].stats[j];
        }
    }
    return {stats: stats, total: total};
};

assert.commandWorked(coll.mapReduce(mapper, reducer, {out: {merge: outputColl.getName()}}));

let resultAsObj = outputColl.convertToSingleObject("value");
assert.eq(2,
          Object.keySet(resultAsObj).length,
          `Expected 2 keys ("1" and "2") in object ${tojson(resultAsObj)}`);
// Use resultsEq() to avoid any assumptions about order.
assert(resultsEq([9, 11, 30], resultAsObj["1"].stats));
assert(resultsEq([9, 41, 41], resultAsObj["2"].stats));

assert(outputColl.drop());

mapper = function() {
    let x = "partner";
    let y = "visits";
    emit(this[x], {stats: [this[y]]});
};

assert.commandWorked(coll.mapReduce(mapper, reducer, {out: {merge: outputColl.getName()}}));

resultAsObj = outputColl.convertToSingleObject("value");
assert.eq(2,
          Object.keySet(resultAsObj).length,
          `Expected 2 keys ("1" and "2") in object ${tojson(resultAsObj)}`);
// Use resultsEq() to avoid any assumptions about order.
assert(resultsEq([9, 11, 30], resultAsObj["1"].stats));
assert(resultsEq([9, 41, 41], resultAsObj["2"].stats));
}());