MongoDB的官网:http://www.mongodb.org/
Windows系统快捷下载地址:http://dl.mongodb.org/dl/win32/x86_64
Linux系统快捷下载地址:http://dl.mongodb.org/dl/linux
安装
windows
- 下载安装包:mongodb-win32-x86_64-3.2.17.zip
- 创建目录:C:\Program Files\MongoDB
- 将zip解压到C:\Program Files\MongoDB,修改文件夹名称mongodb-win32-x86_64-3.2.17->3.2.17
- 创建目录:C:\Program Files\MongoDB\data\db和C:\Program Files\MongoDB\data\log
- 创建文件:C:\Program Files\MongoDB\data\log\MongoDB.log
- 通过cmd执行命令:C:\Program Files\MongoDB\3.2.17\bin>mongod -dbpath “C:\Program Files\MongoDB\data\db”
- 默认端口为:27017
启动服务
- 进入MongoDB的bin目录:cd “C:\Program Files\MongoDB\3.2.17\bin”
- (默认方式) 无需安全校验启动服务:mongod –dbpath “C:\Program Files\MongoDB\data\db”
开启安全验证启动服务:mongod –dbpath “C:\Program Files\MongoDB\data\db” -logpath ” “C:\Program Files\MongoDB\data\db\log\MongoDB.log” -auth
如果开启安全验证启动服务无效,可以尝试重新安装mongod –reinstall –dbpath “E:\mongodb\db” –logpath “E:\mongodb\log\MongoDB.log” –auth
注意:该窗口不能关闭,否则服务将停止。默认是无需安全验证。
登录客户端
- 通过非授权的方式启动:C:\Program Files\MongoDB\3.2.17\bin>mongo
- 创建/切换admin数据库:use admin
在admin库下添加用户:db.createUser({user:”admin”,pwd:”123456”,roles:[“root”]})
安全验证:db.auth(“admin”, “123456”)
引入插件
<!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.6.3</version>
</dependency>
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.MongoTimeoutException;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import org.apache.commons.lang3.StringUtils;
......
// 构建MongoClient
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
build.serverSelectionTimeout(5000); // 最多等待五秒
MongoClientOptions options = build.build();
if (StringUtils.isNotBlank(username)) { // 需要安全认证
MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray());
ServerAddress serverAddress = new ServerAddress(ip, Integer.valueOf(port));
return new MongoClient(serverAddress, credential, options);
} else {// 不需要安全认证
ServerAddress serverAddress = new ServerAddress(ip, Integer.valueOf(port));
return new MongoClient(serverAddress, options);
}
创建集合
命令格式:db.createCollection(name,options)
样例:db.createCollection(“test”)
MongoDatabase mongoDatabase = mongoClient.getDatabase(databaseName);// 获取数据库
mongoDatabase.createCollection(collectionName); // 创建集合