程序需要连接mongodb上传图片

1. D:\mongodb\bin\mongod.exe, 双击启动服务端
访问: http://localhost:27017/ , 显示如下信息表示启动成功
It looks like you are trying to access MongoDB over HTTP on the native driver port.

2. D:\mongodb\bin\mongod.exe, 双击启动客户端, 创建数据库, 创建用户并授权
use chengbin --创建数据库
db.runoob.insert({"name":"菜鸟教程"}) --插入一条记录, 空库不显示
show dbs --查看数据库如下
admin     0.000GB
chengbin  0.000GB
config    0.000GB
local     0.000GB
-- 通过如下命令创建用户名,设置密码,并授权
db.createUser(
	{
	    user:"chengbin",
	    pwd:"chengbin",
	    roles:[{role:"dbOwner",db:"chengbin"}]
	}
)

3. main方法测试连接
public static void main(String[] args) {
	//认证
	MongoCredential credential = MongoCredential.createCredential ("chengbin", "chengbin", "chengbin".toCharArray());
	//连接MongoDB
	ServerAddress serverAddress = new ServerAddress("localhost", 27017);
	MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
	DB db = mongoClient.getDB("chengbin");
	//获取一个集合
	DBCollection coll = db.getCollection("runoob");
	DBObject myDoc = coll.findOne();
	System.out.println(myDoc);
}
-- 控制台打印集合信息如下表示连接成功
Opened connection [connectionId{localValue:2, serverValue:27}] to localhost:27017
{ "_id" : { "$oid" : "6138f941e529ba7f451eac38"} , "name" : "菜鸟教程"}

Logo

一站式 AI 云服务平台

更多推荐