How to get MongoDB collection sharding config using Node.js driver?

297 Views Asked by At

I need to retrieve information about a MongoDB collection's sharding configuration, specifically the shardKey and unique fields. While I can easily obtain this information using the sh.status() command in the MongoDB shell, I haven't been able to figure out how to do this using the MongoDB Node.js driver.

Is it possible to retrieve this information using the Node.js driver, and if so, how can I do it?

I already tried collection.stats(), but no luck. There is a shards object in returned object value but fieds I need aren't there.

  const client = await MongoClient.connect(uri);
  const db = client.db(dbName);
  const stats = await db.collection(collectionName).stats();
2

There are 2 best solutions below

2
Someone Special On

I'm not really sure what are the information you required by you can run the adminCommand equivalent in nodejs using runCommand

e.g.

db.runCommand({ listShards: 1 })

The list of commands u can run for sharding is here.

0
Wernfried Domscheit On

Have a look at

db.getSiblingDB("config").getCollection("collections").find()

It provides the shard key. To get unique fields, you need to query the indexes. Would be this:

db.collection.getIndexes()

You may also have a look at collections config.database, config.shards and , config.chunks