简体   繁体   中英

How do I detect if a MongoDB replica set is not initialised when using the java driver?

I would like to detect if a MongoDB replica set has been initialised yet or not (so I can display an error message to the user like "you forgot to initialise your replica set"). Is it possible to detect if the replica set has been initialised using the Java Mongodb driver? The closest I have found is com.mongodb.Mongo.getReplicaSetStatus() - but I don't think this will tell me if the set is not initialised.

If Mongo ReplicaSet is not initilized rs.status() return error code "94" https://github.com/mongodb/mongo/blob/master/src/mongo/base/error_codes.yml

init_status=$(mongo --quiet -u ${MONGO_ADMIN_USER} -p ${MONGO_ADMIN_PASSWORD} --authenticationDatabase admin --eval "rs.status().code" admin)
if [ "${init_status}" = "94" ]; then
    echo "Mongo ReplicaSet is not initialized"
fi

I can only see old answers here, but I'm surprised that nobody mentioned the ok property. The rs.status() command includes this property in both successful and failed responses. The ok property is set to 1 when the replica set is initialized and 0 when it is not.

Example:

# When Replica Set is initialized
$ mongo --quiet --port 27017 --username your-user --password your-pass --eval 'rs.status().ok'
1

# When Replica Set is NOT initialized
$ mongo --quiet --port 27017 --username your-user --password your-pass --eval 'rs.status().ok'
0

This command works nicely on both primary and secondary nodes.

For more information, check:

This is the command() function you're looking for:

Which gets a String argument.

Note: The 'getReplicaSetStatus' command must be run on the admin database.

http://api.mongodb.org/java/current/com/mongodb/DB.html#command(java.lang.String)

your can directly check the condition :

if(rs.status()) 
{ 
    rs.remove() 
}  

There is another StackOverflow issue that appears to be the same question - See link below. the way to do this would be to get a list of databases that do exist - From the Java driver you could do something like this on a mongod server running on localhost

Mongo mongo = new Mongo( "127.0.0.1", 27017 ); List databaseNames = mongo.getDatabaseNames();

This is equivalent to the mongo shell "show dbs" command.

Check if mongodb database exists?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM