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

如何通过MongoDB Java驱动程序获取分片集群分片数及执行sh.status()

How to Run sh.status() Programmatically & Get Shard Count with MongoDB Java Driver

Got it, let's break this down for you—using the MongoDB Java driver to replicate sh.status() and get your cluster's shard count is totally doable, and I'll walk you through both with practical, easy-to-follow code.

1. Replicating sh.status() in Java

First, keep in mind that sh.status() is a MongoDB Shell helper that wraps several admin commands and queries to the config database to generate a human-readable report. In Java, you can replicate this in two ways:

Option 1: Get Core Shard Details with the listShards Command

This gives you the same shard list and basic metadata that sh.status() displays—perfect if you just need the core shard info:

import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class ShardStatusDemo {
    public static void main(String[] args) {
        // Connect to your sharded cluster (replace with your cluster URI)
        try (MongoClient mongoClient = MongoClients.create("mongodb://your-cluster-host:port")) {
            // Access the admin database (required for sharding-related commands)
            MongoDatabase adminDb = mongoClient.getDatabase("admin");
            
            // Run the listShards command—this is what the shell uses for shard data
            Document shardResults = adminDb.runCommand(new Document("listShards", 1));
            
            // Print the raw result (you can parse and format this for readability)
            System.out.println("Shard Details:");
            System.out.println(shardResults.toJson());
        }
    }
}

Option 2: Replicate the Full sh.status() Report

If you want the complete, detailed output (including sharded databases, chunk distribution, etc.), you'll need to query the config database collections that the shell uses under the hood:

  • config.shards: Shard metadata
  • config.databases: Databases with sharding enabled
  • config.chunks: Chunk distribution across shards

Here's a snippet to fetch and print this data:

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;

// Inside your try-with-resources block (after connecting to the cluster):
MongoDatabase configDb = mongoClient.getDatabase("config");

// Fetch and print all shards
System.out.println("\n--- Shards ---");
MongoCollection<Document> shardsCol = configDb.getCollection("shards");
try (MongoCursor<Document> cursor = shardsCol.find().iterator()) {
    while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
    }
}

// Fetch and print sharded databases
System.out.println("\n--- Sharded Databases ---");
MongoCollection<Document> dbCol = configDb.getCollection("databases");
// Filter to only show databases with sharding enabled
try (MongoCursor<Document> cursor = dbCol.find(new Document("partitioned", true)).iterator()) {
    while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
    }
}

You can format this output to match the shell's sh.status() style by parsing the documents and printing them in a more human-friendly way.

2. Getting the Number of Shards in the Cluster

This is super straightforward—you have two reliable options:

Method 1: Use the listShards Command Result

// After running the listShards command from Option 1:
int shardCount = shardResults.getList("shards", Document.class).size();
System.out.println("\nTotal Shards: " + shardCount);

Method 2: Count Documents in config.shards

// Inside your try-with-resources block:
long shardCount = configDb.getCollection("shards").countDocuments();
System.out.println("\nTotal Shards: " + shardCount);

Both methods work equally well—pick whichever fits your workflow better.


内容的提问来源于stack exchange,提问作者virendra chaudhary

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:03:55