I am a MongoDB newbie, with a MongoDB instance running on a Ubuntu machine.

If I login onto the machine's console and run mongo -u username -p password databasename I have permissions for the database databasename to create and drop collections, insert documents and remove them. I have successfully tested these operations.

However, if I try to insert a document (into the same database using the same user credentials) using the MongoDB API from a Java program (running on the same server), I get error 13:

com.mongodb.MongoCommandException: Command failed with error 13: 
'not authorized on databasename to execute command { insert: "collectionName" ...

My Java code (works well when running on my local machine for another MongoDB instance without authentication):

ServerAddress serverAddress = new ServerAddress(serverName, portNo);
MongoCredential mongoCredential = 
     MongoCredential.createCredential(username, DB_NAME, password.toCharArray());
mongoClient = new MongoClient(...
DB db = mongoClient.getDB("databasename");
mongoCollection = db.getCollection("collectionName");
this.mongoCollection.insert(...                          <-- CAUSES EXCEPTION

What could be the cause of this error, and how can I solve it?

  • Auth is on, so you have to use username and password on mongoclient – Antonios May 22 '15 at 18:17
  • @Antonis: The Java program does use username and password. I have edited the question to better reflect this. – Gruber May 25 '15 at 7:29
  • Is the enableLocalhostAuthBypass set to on? I suspect you are using the localhost exception when trying to access via shell. docs.mongodb.org/v2.6/core/authentication/#localhost-exception . The user is not configured correctly but you bypass it from the localhost. – Antonios May 25 '15 at 12:25
  • @Antonis: Interesting! How can I check the value of enableLocalhostAuthBypass? – Gruber May 25 '15 at 12:44
  • This will reveal the running configuration db.adminCommand( { getParameter : "*" } ) You can change the * with enableLocalhostAuthBypass but the output is usually short and not worth it. – Antonios May 25 '15 at 19:43

The cause of this problem was likely a MongoDB server configuration issue, relating to IP address binding. Changing to resolved the problem.


My problem got solved by restarting the app. I am using PM2 as process manager.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.