Search code examples
mongodbportshardingmongo-shell

Connecting to shards in MongoDB mongo shell


I'm following the tutorial in the MongoDB: The Definitive Guide, 2nd edition, for a databases course, and it appears not to work in version 3.6.2.

Basically I have two mongo shells opened using mongo --nodb.

Then, in the first, I run cluster = new ShardingTest({"shards": 3, "chunksize": 1}) (which works and produces a steady stream of output).

In the second shell, the book says to run db = (new Mongo("localhost:30999")).getDB("test") which fails. I was told by a colleague instead to run db = (new Mongo("localhost:20000")).getDB("test"), which worked.

Then, I inserted data which worked as well. However, when trying sh.status(), I got the message printShardingStatus: this db does not have sharding enabled. be sure you are connecting to a mongos from the shell and not to a mongod.

After searching online, I figured I'd run sh.enableSharding(db) which also gave me the following error:

2018-03-01T11:05:22.654-0500 E QUERY     [thread1] Error: not connected to a mongos :
sh._checkMongos@src/mongo/shell/utils_sh.js:8:15
sh._adminCommand@src/mongo/shell/utils_sh.js:18:9
sh.enableSharding@src/mongo/shell/utils_sh.js:98:12
@(shell):1:1

I'm running on a Windows 10 machine, and have the correct environmental variables set up and the db folder created, so any help/pointers would be much appreciated!

EDIT 1:

This error persists even if db.collection.ensureIndex() is run first.


Solution

  • Try connecting to the shell on port 20006 by opening a new mongo --nodb, then do db = (new Mongo("localhost:20006")).getDB("test")

    This should open the mongos for all the shards, so now the command sh.status() should work, as well as other commands like setting balancer state and starting balancer.