You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过MongoDB Node.js驱动获取集合的分片配置?

获取MongoDB分片集合的shardKey与unique配置(Node.js驱动实现)

可以通过Node.js驱动获取分片集合的shardKey和unique配置,不要用collection.stats()——这个方法返回的是存储层面的统计数据,并不包含分片元信息。分片集合的配置信息存放在MongoDB的config数据库的collections集合中,sh.status()命令本质就是查询这个集合并格式化输出。

具体操作步骤:

  • 连接MongoDB客户端后,切换到config数据库
  • 查询config.collections集合,过滤条件为目标集合的命名空间(格式:数据库名.集合名)
  • 从查询结果中直接提取shardKey和unique字段

完整代码示例:

const { MongoClient } = require('mongodb');

async function getShardConfig(uri, dbName, collectionName) {
  const client = await MongoClient.connect(uri);
  try {
    // 切换到config数据库
    const configDb = client.db('config');
    // 构造集合的命名空间
    const ns = `${dbName}.${collectionName}`;
    // 查询分片配置
    const shardConfig = await configDb.collection('collections').findOne({ ns });
    
    if (!shardConfig) {
      console.log('该集合未分片');
      return null;
    }
    
    // 提取需要的字段
    const result = {
      shardKey: shardConfig.shardKey,
      unique: shardConfig.unique || false // 若未设置unique,默认返回false
    };
    return result;
  } finally {
    await client.close();
  }
}

// 调用示例
getShardConfig('mongodb://your-uri', 'your-db', 'your-collection')
  .then(config => console.log(config))
  .catch(err => console.error(err));

注意事项

  • 执行该操作的MongoDB账号需要有访问config数据库的权限
  • 如果目标集合未分片,findOne会返回null,需要做判断处理

内容的提问来源于stack exchange,提问作者Taras Dubyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:04:58