summaryrefslogtreecommitdiff
path: root/jstests/sharding/hash_crud.js
blob: e88c4fd0491cc1cb02fe6cb54ef6fb58adde78b7 (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
/*
 * Test that crud and find operations target the right shards.
 */
(function() {
'use strict';

load("jstests/sharding/libs/chunk_bounds_util.js");
load("jstests/sharding/libs/find_chunks_util.js");

let st = new ShardingTest({shards: 3});
let dbName = "test";
let collName = "user";
let ns = dbName + "." + collName;
let configDB = st.s.getDB('config');
let testDB = st.s.getDB(dbName);

assert.commandWorked(st.s.adminCommand({enableSharding: dbName}));
st.ensurePrimaryShard(dbName, st.shard1.shardName);
assert.commandWorked(st.s.adminCommand({shardCollection: ns, key: {x: 'hashed'}}));

let chunkDocs = findChunksUtil.findChunksByNs(configDB, ns).toArray();
let shardChunkBounds = chunkBoundsUtil.findShardChunkBounds(chunkDocs);

jsTest.log("Test 'insert'");
// Insert docs that are expected to go to three different shards.
let docs = [{x: -10}, {x: -1}, {x: 10}];
assert.commandWorked(testDB.user.insert(docs));

// Check that the docs are on the right shards and store the shard for each doc.
let shards = [];
for (let doc of docs) {
    let hash = convertShardKeyToHashed(doc.x);
    let shard = chunkBoundsUtil.findShardForShardKey(st, shardChunkBounds, {x: hash});
    assert.eq(1, shard.getCollection(ns).count(doc));
    shards.push(shard);
}
assert.eq(3, (new Set(shards)).size);

jsTest.log("Test 'find'");
assert.eq(3, testDB.user.find({}).count());
assert.eq(2, testDB.user.find({x: {$lt: 0}}).count());

jsTest.log("Test 'update'");
assert.commandWorked(testDB.user.update({x: -10}, {$set: {updated: true}}, {multi: true}));
assert.eq(1, testDB.user.find({x: -10, updated: true}).count());
assert.eq(1, shards[0].getCollection(ns).count({updated: true}));
assert.eq(0, shards[1].getCollection(ns).count({updated: true}));
assert.eq(0, shards[2].getCollection(ns).count({updated: true}));

jsTest.log("Test 'findAndModify'");
assert.commandWorked(
    testDB.runCommand({findAndModify: collName, query: {x: -1}, update: {$set: {y: 1}}}));
assert.eq(1, testDB.user.find({x: -1, y: 1}).count());
assert.eq(0, shards[0].getCollection(ns).count({y: 1}));
assert.eq(1, shards[1].getCollection(ns).count({y: 1}));
assert.eq(0, shards[2].getCollection(ns).count({y: 1}));

jsTest.log("Test 'remove'");
assert.commandWorked(testDB.user.remove({x: 10}));
assert.eq(2, testDB.user.find({}).count());
assert.eq(1, shards[0].getCollection(ns).count({}));
assert.eq(1, shards[1].getCollection(ns).count({}));
assert.eq(0, shards[2].getCollection(ns).count({}));

st.stop();
})();