logger.info("Creating collection " + collectionName); DBCollection collection = db.getCollection(collectionName); collection.createIndex(new BasicDBObject("lineId", "hashed")); if (createDateIndex) { collection.createIndex(new BasicDBObject(shardKey, 1).append("date", 1)); } int shardCount = 1; if (database.isSharded()) { DB configDb = db.getSisterDB("config"); shardCount = (int) configDb.getCollection("shards").count(); DB adminDb = db.getSisterDB("admin"); CommandResult cr = adminDb.command(new BasicDBObject("shardCollection", collection.getFullName()).append("key", new BasicDBObject(shardKey, "hashed")) .append("numInitialChunks", shardCount)); cr.throwOnError(); // Verify it has been correctly distributed // db.chunks.aggregate([{$match: {ns: "telus.wifiCollection_20180410"}}, {$group: {_id: "$shard", count: {$sum: 1}}}]) Cursor cursor = configDb.getCollection("chunks") .aggregate(Arrays.asList(new BasicDBObject[] { new BasicDBObject("$match", new BasicDBObject("ns", collection.getFullName())), new BasicDBObject("$group", new BasicDBObject("_id", "$shard").append("count", new BasicDBObject("$sum", 1))) }), AggregationOptions.builder().outputMode(OutputMode.CURSOR).build()); int n = 0; while (cursor.hasNext()) { cursor.next(); n++; } if (n < shardCount) { logger.fatal("Collection " + collection.getName() + " is distributed on " + n + " shards out of " + shardCount); } else { // Disable balancing for this collection configDb.getCollection("collections").update(new BasicDBObject("_id", collection.getFullName()), new BasicDBObject("$set", new BasicDBObject("noBalance", true))); } }