开发环境
1、Mac
2、IDEA
3、MongoDB 3.6.5
4、Maven
项目实例
1、创建Maven项目mongodb_test,这里不废话
2、pom.xml添加jar依赖,这里用到了两个jar:mongo-java-driver:3.7.0(尽量和你MongoDB版本一致),Junit4.7(我用到了Junit,没用可以不引)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>mongodb_test</groupId>
<artifactId>mongodb_test</artifactId>
<version>1.0-SNAPSHOT</version>
<url>http://maven.apache.org</url>
<dependencies>
<!-- MongoDB连接驱动 -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.7.0</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3、创建MongoDB连接工具类 MongoConnection,其中有两种连接方式:验证用户名+密码,不验证用户名+密码;
package connection;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.List;
/**
* MongoDB连接工具类
* @author lihaoshan
* @date 2018-05-30
* */
public class MongoConnection {
/**
* 需要验证用户名、密码的连接方式
* @return mongoDatabase
* */
public MongoDatabase getConnection(){
try{
//连接到MongoDB服务,如果是远程连接可以将localhost改为服务器所在的IP地址
//ServerAddress()参数分别为服务器地址、端口
ServerAddress serverAddress = new ServerAddress("localhost",27017);
List<ServerAddress> serverAddressList = new ArrayList<ServerAddress>();
serverAddressList.add(serverAddress);
//createScramSha1Credential()参数分别为用户名、数据库名称、密码
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("userName","databaseName","password".toCharArray());
List<MongoCredential> mongoCredentialList = new ArrayList<MongoCredential>();
mongoCredentialList.add(mongoCredential);
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(serverAddressList,mongoCredentialList);
//连接数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
System.out.println("MongoDB连接成功");
return mongoDatabase;
} catch (Exception e){
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return null;
}
/**
* 不需要验证用户名、密码的连接方式
* @return mongoDatabase
* */
public MongoDatabase getConnectionBasis(){
try{
//连接到MongoDB服务
MongoClient mongoClient = new MongoClient("localhost",27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("users");
System.out.println("MongoDB连接成功");
return mongoDatabase;
} catch (Exception e){
System.out.println(e.getClass().getName() + ":" + e.getMessage());
}
return null;
}
}
4、创建junit测试类 MongoDBTest,其中方法为MongoDB的CRUD操作
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import connection.MongoConnection;
import org.bson.Document;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* MongoDB 测试
* @author lihaoshan
* @date 2018-05-30
* */
public class MongoDBTest {
MongoConnection mongoConnection = new MongoConnection();
//连接数据库(不需要验证用户名、密码方式)
MongoDatabase mongoDatabase = mongoConnection.getConnectionBasis();
@Test
public void test(){
MongoCollection<Document> documentCollection = getCollection();
//新增文档
// insertDomcument(documentCollection);
//更新文档
// update(documentCollection);
//删除文档
// delete(documentCollection);
//查询所有文档
findAll(documentCollection);
}
/**
* 获取 集合【对应RDBMS 中的数据表】com.mongodb.client.MongoDatabase.getCollection("集合名")
*/
public MongoCollection<Document> getCollection(){
MongoCollection<Document> collection = mongoDatabase.getCollection("users");
System.out.println("转换到指定集合");
return collection;
}
/**
* 插入文档
* */
public void insertDomcument(MongoCollection<Document> collection){
//创建文档对象com.bson.Document 参数为key-value格式
Document document = new Document();
document.append("name","李汶泽");
document.append("age","28");
List<Document> documentList = new ArrayList<Document>();
documentList.add(document);
collection.insertMany(documentList);
System.out.println("插入文档成功");
}
/**
* 更新 所有文档【表内 数据】com.mongodb.client.MongoCollection<Document>.updateMany()
*/
public void update(MongoCollection<Document> collection){
collection.updateMany(Filters.eq("age", 100), new Document("$set",new Document("age",30)));
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println("更新后的MongoDB数据:"+cursor.next());
}
}
/**
* 删除 文档 com.mongodb.client.MongoCollection<Document>.deleteMany()/deleteOne()
*/
public void delete(MongoCollection<Document> collection){
// 删除符合条件的 第一个文档
collection.findOneAndDelete(Filters.eq("age", 26));
//删除符合条件的 所有文档
// collection.deleteMany(Filters.gte("age", 20));
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> cursor = findIterable.iterator();
while(cursor.hasNext()){
System.out.println("删除后的MongoDB数据:"+cursor.next());
}
}
/**
* 查询 所有文档【表内 数据】com.mongodb.client.MongoCollection<Document>.find()
* 查询 本条数据的时间节点 _id采用ObjectId格式
*
* ObjectId 是一个12字节 BSON 类型数据,有以下格式:
* 前4个字节表示时间戳
* 接下来的3个字节是机器标识码
* 紧接的两个字节由进程id组成(PID)
* 最后三个字节是随机数。
*/
public void findAll(MongoCollection<Document> collection){
/**
* 1. 获取迭代器FindIterable<Document>
* 2. 获取游标MongoCursor<Document>
* 3. 通过游标遍历检索出的文档集合
* */
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
Document document = mongoCursor.next();
System.out.println("MongoDB数据:"+document);
System.out.println("插入时间:"+new SimpleDateFormat().format(document.getObjectId("_id").getDate()));
}
}
}
5、到这里MongoDB的CRUD简单操作就基本完成了,其他的后续再补充;
码云
https://gitee.com/haoshan/mongodb_test