我怎么知道Mongodb查询在哪个节点上运行?

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

连接到MongoDB复制群集时,我想知道查询在哪个节点上运行。

我试图在mongo shell中使用explain(),但是Java驱动程序似乎不支持此命令。

如何使用MongoDB Java驱动程序实现此目的?

mongodb mongodb-java
1个回答
1
投票

您可以尝试使用MongoDB Java驱动程序中的Command Monitoring

public class CustomCommandListener implements CommandListener {
    @Override
    public void commandStarted(final CommandStartedEvent event) {
        System.out.println(String.format("Sent command '%s:%s' with id %s to database" +
            " '%s' on connection '%s' to server '%s'",
            event.getCommandName(),
            event.getCommand().get(event.getCommandName()),
            event.getRequestId(),
            event.getDatabaseName(),
            event.getConnectionDescription().getConnectionId(),
            event.getConnectionDescription().getServerAddress()));
    }
}

也有CommandSucceededEventCommandFailedEvent,但是无论结果如何,您都可以使用上述CommandStartedEvent获得一些详细信息。

然后将此自定义侦听器传递到您的MongoClient设置中;

MongoClientSettings settings = MongoClientSettings.builder()
    .addCommandListener(new CustomCommandListener())
    // other settings
    .build();
MongoClient client = MongoClients.create(settings);

MongoDB Java Driver docs的更多信息>

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