Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB via Java: CommandFailureException, code 18

Tags:

java

mongodb

When running a query on MongoDB from Java, I'm getting following error:

com.mongodb.CommandFailureException: { "serverUsed" : "AAA.BBB.CCC.DDD:27017" , "code" : 18 , "ok" : 0.0 , "errmsg" : "auth fails"}
at com.mongodb.CommandResult.getException(CommandResult.java:76)
at com.mongodb.CommandResult.throwOnError(CommandResult.java:131)
at com.mongodb.DBPort$NativeAuthenticator.authenticate(DBPort.java:652)
at com.mongodb.DBPort.authenticate(DBPort.java:364)
at com.mongodb.DBPort.checkAuth(DBPort.java:375)
at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:291)
at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:271)
at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:84)
at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:66)
at com.mongodb.DBCursor._check(DBCursor.java:458)
at com.mongodb.DBCursor._hasNext(DBCursor.java:546)
at com.mongodb.DBCursor.hasNext(DBCursor.java:571)

When I use the same credentials in RoboMongo, I can connect to the same database.

In Java, I connect to it using following code:

public void init() {
    try {
        final ServerAddress serverAddress = new ServerAddress("AAA.BBB.CCC.DDD", 27017);

        final MongoCredential credential = MongoCredential.createMongoCRCredential("user", 
                "dbName", "password".toCharArray());

        mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));

        db = mongoClient.getDB("dbName");
        state = getPersistenceState();
    } catch (final UnknownHostException exception) {
        LOGGER.error("", exception);
    }
}

I'm using MongoDB 2.4.10 and Mongo Java driver 2.12.2.

How can I modify the code in order to be able to query and modify the database?

like image 247
Dmitrii Pisarenko Avatar asked Dec 31 '25 16:12

Dmitrii Pisarenko


1 Answers

  1. Check that you are able to authenticate and run your queries with mongo shell: "mongo --authenticationDatabase dbName -u user -p"

  2. Look at mongod log and look for failed auth attempts - usually something is wrong

like image 157
Alex Komyagin Avatar answered Jan 02 '26 09:01

Alex Komyagin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!