我是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() );
}
}
}
答案 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());
}
}