skip to Main Content

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

Answers


  1. 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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search