[英]Can't authenticate username with password in MongoDB with Java
I am new to mongodb and I have a bug in authenticating the username and password in mongodb with java. 我是mongodb的新手,并且在用Java验证mongodb中的用户名和密码时遇到错误。 Can anyone tell me the correct source code to connect mongodb with java? 谁能告诉我将mongodb与Java连接的正确源代码? Currently I have an error in getdb 目前我在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() );
}
}
}
You must pass the credentials before you try to 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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.