xander27
xander27

Reputation: 3104

Get shard id for given value of sharding key in mongodb

I have two replica sets in sharding cluster with documents sharded by userId field.

Is there any way to query which shard (replica set) is containgin given document (by _id or sharding key filed) without reimplemnting shadring key hashing on client side

Upvotes: 1

Views: 1482

Answers (1)

Stennie
Stennie

Reputation: 65323

You can use query explain() to identify the shard for a document, by querying based on the shard key.

The winning plan should have a SINGLE_SHARD stage with an equality query similar to the following (with some extra output trimmed for clarity):

> db.users.find({userId:123}).explain().queryPlanner.winningPlan
{
    "stage" : "SINGLE_SHARD",
    "shards" : [
        {
            "shardName" : "shard01",
            "plannerVersion" : 1,
            "namespace" : "test.users",
            "indexFilterSet" : false,
            "parsedQuery" : {
                "userId" : {
                    "$eq" : 123
                }
            },
        }
    ]
}

If you only want the shard name, you can use JavaScript notation to reference the full path:

> db.users.find({userId:123}).explain().queryPlanner.winningPlan.shards[0].shardName
shard01

Upvotes: 3

Related Questions