summaryrefslogtreecommitdiff
path: root/jstests/core/index/indexapi.js
blob: 1b7016ea787d2e0aceb64c841d7bea8b70fbc91f (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
// Cannot implicitly shard accessed collections because of not being able to create unique index
// using hashed shard key pattern.
// @tags: [
//     cannot_create_unique_index_when_using_hashed_shard_key,
//     # Uses $indexStats which is not supported in a transaction.
//     does_not_support_transactions,
// ]
(function() {
"use strict";

const coll = db.indexapi;
coll.drop();

const kTestKeyPattern = {
    x: 1
};

const indexSpecObj = {
    ns: coll._fullName,
    key: kTestKeyPattern,
    name: coll._genIndexName(kTestKeyPattern)
};
assert.eq(indexSpecObj, coll._indexSpec(kTestKeyPattern));

indexSpecObj.name = "bob";
assert.eq(indexSpecObj, coll._indexSpec(kTestKeyPattern, "bob"));

indexSpecObj.name = coll._genIndexName(kTestKeyPattern);
assert.eq(indexSpecObj, coll._indexSpec(kTestKeyPattern));

indexSpecObj.unique = true;
assert.eq(indexSpecObj, coll._indexSpec(kTestKeyPattern, true));
assert.eq(indexSpecObj, coll._indexSpec(kTestKeyPattern, [true]));
assert.eq(indexSpecObj, coll._indexSpec(kTestKeyPattern, {unique: true}));

indexSpecObj.dropDups = true;
assert.eq(indexSpecObj, coll._indexSpec(kTestKeyPattern, [true, true]));
assert.eq(indexSpecObj, coll._indexSpec(kTestKeyPattern, {unique: true, dropDups: true}));

function getSingleIndexWithKeyPattern(keyPattern) {
    let allIndexes = coll.aggregate([
                             {$indexStats: {}},
                             {$match: {key: keyPattern}},
                             // Unnest the "$spec" field into top-level.
                             {$replaceWith: {$mergeObjects: ["$$ROOT", "$spec"]}}
                         ])
                         .toArray();
    assert.eq(allIndexes.length, 1);
    return allIndexes[0];
}

coll.createIndex(kTestKeyPattern, {unique: true});
let allIndexes = coll.getIndexes();
assert.eq(2, allIndexes.length);
assert.sameMembers([kTestKeyPattern, {_id: 1}], allIndexes.map(entry => entry.key));
let xIndex = getSingleIndexWithKeyPattern(kTestKeyPattern);
assert.eq(xIndex.key, kTestKeyPattern);
assert(xIndex.unique, xIndex);

coll.drop();
coll.createIndex(kTestKeyPattern, {unique: 1});
allIndexes = coll.getIndexes();
assert.eq(2, allIndexes.length);
xIndex = getSingleIndexWithKeyPattern(kTestKeyPattern);
assert.eq(kTestKeyPattern, xIndex.key);
assert(xIndex.unique);
}());