1,创建maven项目,并引入以下依赖:
<!--测试包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>compile</scope>
</dependency>
<!--mongodb 同步驱动包-->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.9</version>
</dependency>
2,启动MongoDB服务实例
mongod.exe --dbpath D:\UserData\mongodb --auth
3,获取MongoClient对象
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import java.util.Arrays;
/**
* @Package: com.lcj.mongodb.sync
* @ClassName: MongoUtil
* @Author: Administrator
* @CreateTime: 2021/7/15 15:10
* @Description:
*/
public class MongoUtil {
/**
* 通过指定host和port获得连接
* @return MongoClient
*/
public static MongoClient getInstance1(){
// 添加认证
MongoCredential credential = MongoCredential.createScramSha256Credential("admin", "admin", "123456".toCharArray());
return MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(new ServerAddress("127.0.0.1", 27017))))
.credential(credential)
.build());
}
/**
* 通过连接字符串
* @return MongoClient
*/
public static MongoClient getInstance2(){
return MongoClients.create("mongodb://admin:123456@127.0.0.1:27017/?authSource=admin&authMechanism=SCRAM-SHA-256");
}
}
4,使用Document对象进行CRUD操作
import cn.hutool.core.lang.Console;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertManyResult;
import com.mongodb.client.result.InsertOneResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* @Package: com.lcj.mongodb.sync
* @ClassName: UseDocumentCRUDTest
* @Author: Administrator
* @CreateTime: 2021/7/16 8:26
* @Description:
*/
public class UseDocumentCRUDTest {
// 声明连接对象
private static MongoClient client;
// 声明集合变量
private static MongoCollection<Document> book;
// 所有方法执行前,创建集合对象
@BeforeClass
public static void setUp() {
client = MongoUtil.getInstance1();
// 访问指定的数据库,如果数据库不存在,自动创建
MongoDatabase mongoDatabase = client.getDatabase("test");
// 访问指定的集合,如果集合不存在,在第一次存数据是创建
book = mongoDatabase.getCollection("book");
}
// 所有方法执行完后,释放资源
@AfterClass
public static void close() {
book.drop();
client.close();
}
/**
* 插入单个文档
*/
@Test
public void insertOne() {
// 创建如下文档
/*
{
"name" : "MongoDB",
"type" : "type",
"count" : 1,
"versions": [ "v3.2", "v3.0", "v2.6" ],
"info" : { x : 203, y : 102 }
}
*/
Document document = new Document("name", "MongoDB")
.append("type", "type")
.append("count", 1)
.append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
.append("info", new Document("x", 203).append("y", 102));
// 插入单个文档,如果未指定_id字段,会自动添加
InsertOneResult insertOneResult = book.insertOne(document);
if (insertOneResult.wasAcknowledged()) {
Console.log("插入数据成功,文档id:{}", insertOneResult.getInsertedId().toString());
} else {
System.out.println("插入文档失败");
}
}
/**
* 插入多个文档
*/
@Test
public void insertMany() {
List<Document> documents = new ArrayList<>(100);
for (int i = 1; i <= 100; i++) {
documents.add(new Document("i", i));
}
// 插入文档,如果未指定_id字段,会自动添加
InsertManyResult insertManyResult = book.insertMany(documents);
if (insertManyResult.wasAcknowledged()) {
Console.log("插入数据成功,文档id:{}", insertManyResult.getInsertedIds());
} else {
System.out.println("插入文档失败");
}
}
/**
* 查询集合的第一个文档
*/
@Test
public void findFirst() {
Document first = book.find().first();
if (Objects.nonNull(first)) {
System.out.println(first.toJson());
}
}
/**
* 查询集合的所有文档
*/
@Test
public void findAll() {
// 返回一个游标
try (MongoCursor<Document> iterator = book.find().iterator()) { // 防止游标泄露
// 遍历数据
while (iterator.hasNext()) {
Document next = iterator.next();
System.out.println(next.toJson());
}
}
}
/**
* 查询item字段,值为postcard的第一个文档
*/
@Test
public void findFirstByFilter() {
Document first = book.find(Filters.eq("item", "postcard")).first();
if (Objects.nonNull(first)) {
System.out.println(first.toJson());
}
}
/**
* 查询i字段,值超过50的所有文档
*/
@Test
public void findAllByFilterGt() {
// 返回一个游标
try (MongoCursor<Document> iterator = book.find(Filters.gt("i", 50)).iterator()) { // 防止游标泄露
// 遍历数据
while (iterator.hasNext()) {
Document next = iterator.next();
System.out.println(next.toJson());
}
}
}
/**
* 查询i字段,值在60到80之间
*/
@Test
public void findAllByFilterAnd() {
// 返回一个游标
try (MongoCursor<Document> iterator = book.find(Filters.and(Filters.gte("i", 60), Filters.lte("i", 80))).iterator()) { // 防止游标泄露
// 遍历数据
while (iterator.hasNext()) {
Document next = iterator.next();
System.out.println(next.toJson());
}
}
}
// 更新单个文档
@Test
public void updateOne() {
UpdateResult updateResult = book.updateOne(Filters.eq("i", 50), Updates.set("i", 500));
}
/**
* 更新字段i小于50的,将匹配的值加上100
*/
@Test
public void updateMany() {
UpdateResult updateResult = book.updateMany(Filters.lt("i", 50), Updates.inc("i", 100));
Console.log("更新数量:{}", updateResult.getModifiedCount());
}
/**
* 删除单个文档
*/
@Test
public void deleteOne() {
DeleteResult deleteResult = book.deleteOne(Filters.eq("i", 50));
Console.log("删除数量: {}", deleteResult.getDeletedCount());
}
/**
* 删除多个文档
*/
@Test
public void deleteMany() {
DeleteResult deleteResult = book.deleteMany(Filters.eq("name", "MongoDB"));
Console.log("删除数量: {}", deleteResult.getDeletedCount());
}
}
5,单测结果
image-20210716085918796
网友评论