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?
Best Answer
The cause of this problem was likely a MongoDB server configuration issue, relating to IP address binding. Changing 127.0.0.1 to 0.0.0.0 resolved the problem.