Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

How do you shard a collection with the Go driver?

I am looking for a way to shard a collection (https://docs.mongodb.com/manual/reference/method/sh.shardCollection/) using the Go driver (https://github.com/mongodb/mongo-go-driver).

I was somehow expecting a method db.ShardCollection(...) or collection.Shard(...) but I couldn’t find anything.

I suppose it would work using db.RunCommand? But is there a more Go idiomatic way?

Thanks,
Iulian

Hi @Iulian_Nitescu,

Sharding a collection is usually considered an administrative task that users would do once using the shell or another tool, so drivers don’t offer a helper for it. You can do this using db.RunCommand. The command document should be based on the information at https://docs.mongodb.com/manual/reference/command/shardCollection/. It would look something like this:

cmd := bson.D{
    {"shardCollection", "dbName.collectionName",
    {"key", bson.D{{"firstKeyField", 1}, {"secondKeyField", 1}, ...},
    {"unique", true},
    {"numInitialChunks", 5},
}
err := db.RunCommand(ctx, cmd).Err()
// handle error

– Divjot

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.