1

I am fetching metrics about my mongo application and want to fetch replication oplog metrics using Mongo Java client.

From the terminal printReplicationInfo() command gives the required info. However I am not able to find it's equivalent to fetch the same data from Mongo Java client.

Some old pages claim this is not possible though Java client, wondering if the new client has any such options. Any help here would be appreciated.

Update: thanks for the suggestion, here is my attempt to fetch oplog window information:

        DB db = mongoClient.getDB("local");
        DBCollection collection = db.getCollection("oplog.rs");
        List<DBObject> dbObjects = collection.find().sort(new 
        BasicDBObject("ts",-1)).toArray();
        DBObject startEntry = dbObjects.get(0);
        DBObject lastEntry = dbObjects.get(dbObjects.size()-1);
        String startTime = (String)startEntry.get("ts");
        String endTime = (String)lastEntry.get("ts");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy.MM.dd");
        Date startDate = simpleDateFormat.parse(startTime);
        Date endDate = simpleDateFormat.parse(endTime);
        long diff = endDate.getTime() - startDate.getTime();
RohitS
  • 157
  • 2
  • 6
  • 21
  • Possible duplicate of https://stackoverflow.com/questions/27964050/mongodb-db-getreplicationinfo-with-java-driver – kevinadi Jun 05 '19 at 23:10
  • In the shell, `db.printReplicationInfo()` just calls `db.getReplicationInfo()`, which is defined in https://github.com/mongodb/mongo/blob/v4.0/src/mongo/shell/db.js#L1106-L1171. It's basically a JS function that calculates all the numbers. Since this is a shell helper, it's not available in the driver. If you need to do this in Java, you would need to translate the aforementioned JS source into Java. – kevinadi Jun 05 '19 at 23:17

1 Answers1

1

You can try out this,

DB db = mongoClient.getDatabase("local");
DBObject cmd = new BasicDBObject();
cmd.put("getReplicationInfo", 1);
CommandResult result = db.command(cmd);

Or in newer API version, use Document class is from package org.bson

DB db = mongoClient.getDatabase("admin");
Document documentA = db.runCommand(new Document("getReplicationInfo",1));