无法使用Java在MongoDB中使用密码验证用户名

时间:2016-09-06 10:53:31

标签: java mongodb

我是mongodb的新手,我在使用java验证mongodb中的用户名和密码时遇到了错误。谁能告诉我连接mongodb和java的正确源代码?目前我在getdb

中有错误
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;  

public class Javamongodbconnection {
   public static void main( String args[] ) {       
      try{          

         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
         DB db = mongoClient.getDB( "company" );
         System.out.println("Connect to database successfully");
         boolean auth = authenticate("Dell", "syzygy");
         System.out.println("Authentication: "+auth);

      } catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
}  

1 个答案:

答案 0 :(得分:0)

在尝试getDB之前,您必须先传递凭据...

private void main() {
    try {
        ArrayList<MongoCredential> credentials = new ArrayList<>();
        credentials.add(MongoCredential.createCredential("username", "company", "password".toCharArray()));

        MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), credentials);
        DB db = mongoClient.getDB("company");
        System.out.println("Connect to database successfully");
        //boolean auth = authenticate("Dell", "syzygy");
        //System.out.println("Authentication: "+auth);
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}