如何从 cli 获取连接到 mongodb 集群的所有主机的列表

问题描述 投票:0回答:1

我有一个 mongodb 集群,每个集群有 5 个分片,每个分片有 3 个副本集,还有配置服务器的副本集和一些 mongoses 服务器。有没有办法从命令行 mongosh 我可以获得这个集群的所有主机的列表?

如果我尝试 sh.status() 它只会向我显示分片信息,而不是 mongoses 或配置服务器的主机

mongodb mongodb-query mongo-shell
1个回答
0
投票

您可以查询的

mongos
服务器

db.getSiblingDB('config').mongos.find({}, { _id: 1 })

对于分片和配置服务器,使用

db.adminCommand("getShardMap")

db.adminCommand("getShardMap").map
{
  shard_01: 'shard_01/d-mipmdb-sh1-01:27018,d-mipmdb-sh2-01:27018',
  shard_02: 'shard_02/d-mipmdb-sh1-02:27018,d-mipmdb-sh2-02:27018',
  shard_03: 'shard_03/d-mipmdb-sh1-03:27018,d-mipmdb-sh2-03:27018',
  shard_04: 'shard_04/d-mipmdb-sh1-04:27018,d-mipmdb-sh2-04:27018',
  config: 'configRepSet/d-mipmdb-cfg-01:27019,d-mipmdb-cfg-02:27019,d-mipmdb-cfg-03:27019'
}

但是,它没有列出任何 ARBITER。如果您还需要列出 ARBITER,那么您必须连接到每个分片并查询副本集配置。可以这样做:

function getConnectionURL(uri) {
   const mongoURI = require("mongodb-uri");
   const uriObj = mongoURI.parse(db.getMongo()._connectionInfo.connectionString);

   let ret = { scheme: 'mongodb', options: { readPreference: 'primaryPreferred' } };
   if (uri.includes('/')) {
      ret.hosts = uri.split('/').pop().split(',').map(x => { let h = x.split(':'); return { host: h[0], port: h[1] } })
      ret.options.replicaSet = uri.split('/').shift();
   } else {
      ret.hosts = uri.split(',').map(x => { let h = x.split(':'); return { host: h[0], port: h[1] } })
   }

   for (let k of ['database', 'password', 'username'])
      if (uriObj[k] != undefined) ret[k] = uriObj[k];

   for (let k of ['tls', 'authSource', 'authMechanism', 'tlsCertificateKeyFile', 'tlsCAFile'])
      if (uriObj.options[k] != undefined) ret.options[k] = uriObj.options[k];

   if (ret.options.tlsCAFile == undefined && ret.options.tls == 'true') {
      const cmdLineOpts = db.serverCmdLineOpts().parsed;
      if (cmdLineOpts.net.tls != undefined && cmdLineOpts.net.tls.CAFile != undefined) {
         ret.options.tlsCAFile = cmdLineOpts.net.tls.CAFile;
      } else {
         ret.options.tlsCAFile = '/etc/ssl/certs/ca-bundle.crt';
      }
   }

   return mongoURI.format(ret);
}


const map = db.adminCommand("getShardMap").map;
for (let rs of Object.keys(map)) {
   const replicaSet = Mongo(getConnectionURL(map[rs])).getDB("admin");
   print(replicaSet.adminCommand({ replSetGetConfig: 1 }).config.members.map(x => x.host));
}

注意,当您使用 Mongo() 时,

sh.status()
不起作用,您必须使用
adminCommand({ replSetGetStatus: 1 })
做同样的事情。

© www.soinside.com 2019 - 2024. All rights reserved.