mongodb-base

文章目录
  1. 1. 安装步骤(centos7)
  2. 2. 基本操作->java api的crud
安装步骤(centos7)
1.下载安装包
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-3.2.10.tgz
2.解压安装包
tar -zxvf mongodb-linux-x86_64-rhel62-3.2.10.tgz
3.将解压目录移动到(/usr/local/mongodb)
mv mongodb-linux-x86_64-rhel62-3.2.10 /usr/local/mongodb
4.在/usr/local/mongodb目录下创建/data/db目录和/logs目录
mkdir -p /usr/local/mongodb/data/db
mkdir -p /usr/local/mongodb/logs
5.在/usr/local/mongodb/logs目录下创建mongodb.log文件
touch mongodb.log
6.在/usr/local/mongodb/bin目录下创建mongodb的配置文件
touch mongodb.conf
7.编辑mongodb.conf文件
vi mongodb.conf
编辑内容
dbpath = /usr/local/mongodb/data/db #数据文件存放目录
logpath = /usr/local/mongodb/logs/mongodb.log #日志文件存放目录
port = 27017 #端口
fork = true #以守护程序的方式启用,即在后台运行
nohttpinterface = true
auth=true
bind_ip=0.0.0.0
8.修改环境变量
vi /etc/profile
添加的内容
export MONGODB_HOME=/usr/local/mongodb
export PATH=$PATH:$MONGODB_HOME/bin
9.编辑完成之后重启系统配置
source /etc/profile
10.在/usr/local/mongodb/bin目录下启动mongodb
./mongod -f mongodb.conf
11.关闭mongodb服务
./mongod -f ./mongodb.conf --shutdown
12.开启27017端口

13.使用shell登录到mongodb
./mongodb

14.登录到相关数据库
use test

15.创建用户
db.createUser(
{
user: "test",
pwd: "test",
roles: [{ role: "readWrite", db: "test" }]
}
)
16.修改配置,开启验证
auth=true
17.重启服务
停止服务,然后启动
18.登录
./mongodb
19.验证
auth('test', 'test')(返回1代表成功)
20.操作
db.user.find()
db.user.insert({"name":'jack',"age": 12})
基本操作->java api的crud
1. 引入依赖
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.9.1</version>
</dependency>

2.java代码
// 工具类
public class MongoUtil {
private static String baseUrl = "192.168.25.147:27017";
private static String userName = "test";
private static String passWord = "test";
private static final String url = "mongodb://"+ userName +":"+ passWord + "@"+ baseUrl + "/";

// 获取MongoDatabase
public static MongoDatabase getConnection(String dataName) {
// 获取MongoClient
com.mongodb.client.MongoClient mongoClient = MongoClients.create(url + dataName);
// 获取MongoDatabase
MongoDatabase db = mongoClient.getDatabase(dataName);
return db;
}
}

// 基本操作 -> 获取所有
public static void findAll(String databaseName, String collectionName) {
MongoDatabase database = MongoUtil.getConnection(databaseName);
MongoCollection<Document> collection = database.getCollection(collectionName);
FindIterable<Document> documents = collection.find();
print(documents);
}

// 基本操作 -> 插入
public static void insert(String databaseName, String collectionName) {
// 获取database
MongoDatabase database = MongoUtil.getConnection(databaseName);
// 获取Clooection
MongoCollection<Document> collection = database.getCollection(collectionName);
// 创建Document
Document document = new Document()
.append("name", "mick11")
.append("age", "33")
.append("address", "长沙")
.append("sex", "男");
// 插入document
collection.insertOne(document);
}


// 打印所有
public static void print(FindIterable<Document> documents) {
for (Document document : documents) {
System.out.println(document.toJson());
}
}