Search code examples
mongodbsharding

MongoDB sharding working on only one instace


I have created three mongodb instances on localhost with different port like

mongod.exe --config C:\MongoDB2.6\mongod.cfg

mongod.exe --config D:\MongoDB2.6\mongodinst1.cfg

mongod.exe --config E:\MongoDB2.6\mongodinst2.cfg

These 3 are getting instantiated successfully (running on port 2021,2022,2023). Now I am using the mongos command for clustering for these three instance and my command is like this

mongos.exe --configdb 127.0.0.1:2021,127.0.0.1:2022,127.0.0.1:2023

It is syncing the three mongodb instances successfully. now I am connecting to the mongos instance on port 27017 and creating the shard

 sh.addShard("127.0.0.1:2021")
 sh.addShard("127.0.0.1:2022")
 sh.addShard("127.0.0.1:2023")

This process is also successful. After this on the mongos instance (27017), I am creating one db(myshard) and collection(mycoll).

Now I insert data into this collection:

db.myshard.insert([
...
{
   title: 'NoSQL Database', 
   description: 'NoSQL database doesn',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 20, 
   comments: [  
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2013,11,10,2,35),
         like: 0 
      }
   ]
},
...
])

Now it is reflecting the these values to me on my one of the instances running on port 2021 but not on others instance like 2022 and 2023 port.

I am new to mongodb and not understanding why it is happening like this. Could someone please explain this behavior?


Solution

  • Basically what is happening here is that the sharded cluster is deciding which shard to use according to your shard key (defaults to _id). You don't necessarily know ahead of time which shard is going to be used and where exactly the document will be stored.

    This "issue" is handled by mongos and the config servers. The config servers hold meta information about your cluster, for example, where the data is located within your sharded cluster.

    In order to take advantage of the sharding mechanism, all of your queries should be executed on the mongos shell. This is the only method that you can use to extract any data from anyone of your shards. The mongos shell will query your databases and collections according the meta information that your config servers contains.