Search code examples
mongodbmongodb-java

How can I know Mongodb query runs on which node?


When connecting to a MongoDB replication cluster, I want to know which node the query runs on.

I tried to use explain() in mongo shell, but the Java driver doesn't seem to support this command.

How can I achieve this using MongoDB Java Driver?


Solution

  • You can try utilizing Command Monitoring from MongoDB Java Driver;

    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()));
        }
    
        @Override
        public void commandSucceeded(CommandSucceededEvent event) {
            //ignore
        }
    
        @Override
        public void commandFailed(CommandFailedEvent event) {
            //ignore
        }
    }
    

    There are also CommandSucceededEvent and CommandFailedEvent, but regardless of its result, you can get some details with the CommandStartedEvent as above.

    Then pass this custom listener into your MongoClient settings;

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

    More on MongoDB Java Driver docs