2

I gave role for DB purp is UserAdmin,I run server with mongod --auth --dbpath c:\mongodb\data\db. First I done a java file in eclipse to connect DB,it worked properly.

After I create and run the below file in eclipse:

try {

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("purplista");
    boolean auth =db.authenticate("purp","123".toCharArray());
    System.out.println("Connect to database successfully");

    DBCollection doc = db.getCollection("test");
    System.out.println("Collection test selected successfully..");

    DBCursor cursor = doc.find();
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
   }  catch (Exception e) {
e.printStackTrace();

}

got error like this:

Connect to database successfully..

Collection test selected successfully..

com.mongodb.MongoException: not authorized for query on purplista.test at com.mongodb.QueryResultIterator.throwOnQueryFailure(QueryResultIterator.java:214) at com.mongodb.QueryResultIterator.init(QueryResultIterator.java:198) at com.mongodb.QueryResultIterator.initFromQueryResponse(QueryResultIterator.java:176) at com.mongodb.QueryResultIterator.(QueryResultIterator.java:64) at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:80) at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:61) at com.mongodb.DBCursor._check(DBCursor.java:458) at com.mongodb.DBCursor._hasNext(DBCursor.java:546) at com.mongodb.DBCursor.hasNext(DBCursor.java:571) at purplista.FindDoc.main(FindDoc.java:34)

zohar
  • 2,298
  • 13
  • 45
  • 75
sak91
  • 23
  • 1
  • 3
  • It looks like you are not authenticating. Have you added the user ? http://stackoverflow.com/questions/4881208/how-to-put-username-password-in-mongodb – Kenneth Clark Apr 30 '14 at 12:14
  • You mongoDb may be running secure mode . just check with boolean auth = db.authenticate("db", "password".toCharArray()); – Sumeet Kumar Yadav Apr 30 '14 at 12:14

1 Answers1

2

A couple of issues I see are:

  1. You are not checking the return value of db.authenticate() which may be returning false if it fails to authenticate.
  2. Even if authenticated, you may not have appropriate permissions to perform the intended operations (in your case read) on the specified database.

A few things to check:

  1. Is this a valid user / password - may be try mongo shell using the same credentials
  2. If valid, does it have appropriate permissions on the database you are using? Since you can create users in "admin" database that can be used to authenticate, however those users may not be setup for additional access that you need for your operations.
  3. If you are using MongoDB v2.6, all the users must be in "admin" database.
  4. You can check for "system.users" collection under the database of interest (test) and admin database to check where the user is setup.
aks
  • 720
  • 4
  • 9