Reputation: 7328
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.
Upvotes: 4
Views: 5639
Reputation: 7727
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:
Upvotes: 1
Reputation: 21
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
Upvotes: 2
Reputation: 434
your can directly check the condition :
if(rs.status())
{
rs.remove()
}
Upvotes: 1
Reputation: 10794
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)
Upvotes: 0
Reputation: 1034
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?
Upvotes: -1