summaryrefslogtreecommitdiff
path: root/jstests/aggregation/bugs/server533.js
blob: d66c5d27ad83353cb0307b326712404699d6fc8a (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
// SERVER-533: Aggregation stage to randomly sample documents.

// For assertErrorCode.
load('jstests/aggregation/extras/utils.js');

(function() {
'use strict';

var coll = db.agg_sample;
coll.drop();

// Should return no results on a collection that doesn't exist. Should not crash.
assert.eq(coll.aggregate([{$sample: {size: 10}}]).toArray(), []);

var nItems = 3;
for (var i = 0; i < nItems; i++) {
    assert.writeOK(coll.insert({_id: i}));
}

[0, 1, nItems, nItems + 1].forEach(function(size) {
    var results = coll.aggregate([{$sample: {size: size}}]).toArray();
    assert.eq(results.length, Math.min(size, nItems));
});

// Multiple $sample stages are allowed.
var results = coll.aggregate([{$sample: {size: nItems}}, {$sample: {size: 1}}]).toArray();
assert.eq(results.length, 1);

// Invalid options.
assertErrorCode(coll, [{$sample: 'string'}], 28745);
assertErrorCode(coll, [{$sample: {size: 'string'}}], 28746);
assertErrorCode(coll, [{$sample: {size: -1}}], 28747);
assertErrorCode(coll, [{$sample: {unknownOpt: true}}], 28748);
assertErrorCode(coll, [{$sample: {/* no size */}}], 28749);
}());