summaryrefslogtreecommitdiff
path: root/jstests/core/group4.js
blob: 2465274c027f85fd55b7aa3111785b0fcf4f3407 (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

t = db.group4;
t.drop();

function test(c, n) {
    var x = {};
    c.forEach(function(z) {
        assert.eq(z.count, z.values.length, n + "\t" + tojson(z));
    });
}

t.insert({name: 'bob', foo: 1});
t.insert({name: 'bob', foo: 2});
t.insert({name: 'alice', foo: 1});
t.insert({name: 'alice', foo: 3});
t.insert({name: 'fred', foo: 3});
t.insert({name: 'fred', foo: 4});

x = t.group({
    key: {foo: 1},
    initial: {count: 0, values: []},
    reduce: function(obj, prev) {
        prev.count++;
        prev.values.push(obj.name);
    }
});
test(x, "A");

x = t.group({
    key: {foo: 1},
    initial: {count: 0},
    reduce: function(obj, prev) {
        if (!prev.values) {
            prev.values = [];
        }
        prev.count++;
        prev.values.push(obj.name);
    }
});
test(x, "B");