1、创建连接用户
> mongo ip:port
> use test
> db.addUser("root", "123456")
> db.auth("root","123456") (登陆验证)
2、java连接mongodb的驱动,下载地址:https://github.com/mongodb/mongo-java-driver/downloads。
3、测试代码
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class Util {
/**
* @param args
* @throws MongoException
* @throws UnknownHostException
*/
public static void main(String[] args) {
Mongo m;
try {
m = new Mongo("192.168.86.1", 27027); //<span style="font-family: Arial;">192.168.86.1为Ip,27027mongoDB的端口</span>
DB db = m.getDB("test");
if(db.authenticate("root", "123456".toCharArray())){
System.out.println("success");;
}
else System.out.println("false");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MongoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}