Search code examples
mongodbsharding

how to get results from different shards and same collection


I created a test MongoDB Sharding with 1 Config Server, 1 Router and 2 Shards.

I created a config server with mongod --configsvr --dbpath /data/configdb --port 27019

And I run mongos with mongos --configdb <CONFIG SERVER IP>:27019. I connected shards and database and collections. When I query sharded collection, cursor doesn't get results from two shards, it gets results only 1 shard. According to MongoDB Sharding Document, I can distribute a collection to different shards but results didn't satisfy this information.

What am I doing wrong? What's the correct way to get results from different shards with same query?


Solution

  • The correct way is to ensure that you do NOT have to go cross shard, often. You chose a shard key so that your queries for not end up going across shards. e.g. a user database could have user id/name as the shard key. Most queries go looking for a single user, so would come back from single shard.

    For queries that cannot be satisfied with results from 1 shard alone, Mongo automatically requests data from all shards.