[!NOTE]
本教程是《SpringBoot系列基础教程》之一,教程目录:https://blog.csdn.net/laisc7301/article/details/135918617
首先按照图示新建项目:
添加以下依赖:
找到application.properties文件,并写入下面内容:
server.port=8001
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/mytest
整个项目的文件结构如下图所示:
把代码贴出来,因为代码里的注释写得比较详细,这里就不多说了。
TestController.java
package com.laisc.example4.controller;
import com.laisc.example4.entity.User;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import jakarta.annotation.Resource;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/test")
public class TestController {
@Resource
private MongoTemplate mongoTemplate;
@ResponseBody
@RequestMapping("/create")
public String createCollection() { //创建集合
// 设置集合名称
String collectionName = "test1";
// 创建集合并返回集合信息
mongoTemplate.createCollection(collectionName);
// 检测新的集合是否存在,返回创建结果
return mongoTemplate.collectionExists(collectionName) ? "创建视图成功" : "创建视图失败";
}
@ResponseBody
@RequestMapping("/get1")// 执行获取集合名称列表
public String getCollectionNames() {
return mongoTemplate.getCollectionNames().toString();
}
@ResponseBody
@RequestMapping("/get2")
public String collectionExists() {// 检测集合是否存在
String collectionName = "test1";//集合名
return mongoTemplate.collectionExists(collectionName) ? "集合存在" : "集合不存在";
}
@ResponseBody
@RequestMapping("/delall")
public Object dropCollection() { //删除集合
// 设置集合名称
String collectionName = "test1";
// 执行删除集合
mongoTemplate.getCollection(collectionName).drop();
// 检测集合是否存在,返回删除结果
return !mongoTemplate.collectionExists(collectionName) ? "删除集合成功" : "删除集合失败";
}
@ResponseBody
@RequestMapping("/insert")
public Object insert() { // 插入文档
// 设置用户信息
User u = new User();
u.setId(100);
u.setUsername("admin");
u.setPassword("123");
// 插入一条用户数据,如果文档信息已经存在就抛出异常
User u2 = mongoTemplate.insert(u, "test2");
return u2; // 输出存储结果
}
@ResponseBody
@RequestMapping("/save")
public Object save() { // 插入文档
// 设置用户信息
User u = new User();
u.setId(100);
u.setUsername("admin");
u.setPassword("abcd");
// 存储用户信息,如果文档信息已经存在就执行更新
User u2 = mongoTemplate.save(u, "test2");
// 输出存储结果
System.out.println("存储的用户信息为:" + u2);
//log.info("存储的用户信息为:{}", newUser);
return u2.toString();
}
/**
* insert和save的区别
* 插入重复数据
*
* insert: 若新增数据的主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException 异常提示主键重复,不保存当前数据。
* save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作。
* 批操作
*
* insert: 可以一次性插入一整个列表,而不用进行遍历操作,效率相对较高
* save: 需要遍历列表,进行一个个的插入
**/
@ResponseBody
@RequestMapping("/findall")
public String findAll() { // 执行查询集合中全部文档信息
// 执行查询集合中全部文档信息
List<User> documentList = mongoTemplate.findAll(User.class, "test2");
// 输出结果
return documentList.toString();
}
@ResponseBody
@RequestMapping("/findbyid")
public String findById() { // 根据文档ID查询集合中文档数据
// 设置查询的文档 ID
int id = 100;
// 根据文档ID查询集合中文档数据,并转换为对应 Java 对象
User u = mongoTemplate.findById(id, User.class, "test2");
return u.toString();
}
@ResponseBody
@RequestMapping("/findone")
public String findOne() { // 查询,但只输出第一条查询结果
// 设置查询条件参数
String username = "admin";
// 创建条件对象
Criteria criteria = Criteria.where("username").is(username);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 查询一条文档,如果查询结果中有多条文档,那么就取第一条
User user = mongoTemplate.findOne(query, User.class, "test2");
return user.toString();
}
@ResponseBody
@RequestMapping("/findmany")
public String findByCondition() { // 查询
// 设置查询条件参数
String username = "admin";
// 创建条件对象
Criteria criteria = Criteria.where("username").is(username);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 查询并返回结果
List<User> documentList = mongoTemplate.find(query, User.class, "test2");
return documentList.toString();
}
@ResponseBody
@RequestMapping("/findmany2")
public String findByCondition2() { // 查询,并按照age字段的值升序排序
// 设置查询条件参数
String username = "admin";
// 创建条件对象
Criteria criteria = Criteria.where("username").is(username);
// 创建查询对象,然后将条件对象添加到其中,并按照age字段的值升序排序。
Query query = new Query(criteria).with(Sort.by("age").ascending());
// 查询并返回结果
List<User> documentList = mongoTemplate.find(query, User.class, "test2");
return documentList.toString();
}
@ResponseBody
@RequestMapping("/find2")
public String findByExistsField() { //查询存在指定字段的值的文档数据
// 设置查询条件参数
String field = "username";
// 创建条件
Criteria criteria = Criteria.where(field).exists(true);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 查询并返回结果
List<User> documentList = mongoTemplate.find(query, User.class, "test2");
return documentList.toString();
}
@ResponseBody
@RequestMapping("/update1")
public String update() { //更新集合中【匹配】查询到的第一条文档数据,如果没有找到就【创建并插入一个新文档】
// 创建条件对象
Criteria criteria = Criteria.where("username").is("admin");
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 创建更新对象,并设置更新的内容
Update update = new Update().set("username", "root").set("password", "q123");
// 执行更新,如果没有找到匹配查询的文档,则创建并插入一个新文档
UpdateResult result = mongoTemplate.upsert(query, update, User.class, "test2");
// 输出结果信息
String resultInfo = "";
if (result.getMatchedCount() > 0) {
resultInfo = "匹配到1条数据,对第一条数据进行了更改";
} else {
resultInfo = "未匹配到数据,插入了一个新文档";
}
return resultInfo;
}
@ResponseBody
@RequestMapping("/update2")
public String updateFirst() {// 更新集合中【匹配】查询到的【文档数据集合】中的【第一条数据】
// 创建条件对象
Criteria criteria = Criteria.where("username").is("admin");
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 创建更新对象,并设置更新的内容
Update update = new Update().set("username", "a123").set("password", "a456");
// 执行更新
UpdateResult result = mongoTemplate.updateFirst(query, update, User.class, "test2");
String resultInfo = "共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据";
return resultInfo;
}
@ResponseBody
@RequestMapping("/updatemany")
public String updateMany() { // 更新所有符合条件的文档
// 创建条件对象
Criteria criteria = Criteria.where("username").is("admin");
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 设置更新字段和更新的内容
Update update = new Update().set("username", "root").set("password", "b123");
// 执行更新
UpdateResult result = mongoTemplate.updateMulti(query, update, User.class, "test2");
// 输出结果信息
String resultInfo = "总共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据";
return resultInfo;
}
@ResponseBody
@RequestMapping("/remove")
public String remove() { // 执行删除匹配的全部文档信息
// 设置查询条件参数
int age = 30;
// 创建条件对象
Criteria criteria = Criteria.where("username").is("admin").and("age").is(8);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 执行删除查找到的匹配的全部文档信息
DeleteResult result = mongoTemplate.remove(query, "test2");
// 输出结果信息
String resultInfo = "成功删除 " + result.getDeletedCount() + " 条文档信息";
return resultInfo;
}
@ResponseBody
@RequestMapping("/remove2")
public String findAndRemove() { // 执行删除查找到的匹配的第一条文档,并返回删除的文档信息
// 创建条件对象
Criteria criteria = Criteria.where("username").is("admin");
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 执行删除查找到的匹配的第一条文档,并返回删除的文档信息
User result = mongoTemplate.findAndRemove(query, User.class, "test2");
// 输出结果信息
String resultInfo = "";
if (result != null) {
resultInfo = "成功删除文档信息,文档内容为:" + result.toString();
} else {
resultInfo = "找不到该文档。";
}
return resultInfo;
}
@ResponseBody
@RequestMapping("/createindex")
public String createAscendingIndex() { // 创建索引
// 设置字段名称
String field = "username";
// 创建索引
return mongoTemplate.getCollection("test2").createIndex(Indexes.ascending(field));
}
@ResponseBody
@RequestMapping("/createindex2")
public String createUniqueIndex() { // 创建唯一索引
// 设置字段名称
String indexName = "password";
// 配置索引选项
IndexOptions options = new IndexOptions();
// 设置为唯一索引
options.unique(true);
// 创建索引
return mongoTemplate.getCollection("test2").createIndex(Indexes.ascending(indexName), options);
}
@ResponseBody
@RequestMapping("/getindex")
public String getIndexAll() { // 获取集合中全部索引信息
// 获取集合中所有列表
ListIndexesIterable<Document> indexList = mongoTemplate.getCollection("test2").listIndexes();
// 创建字符串集合
List<org.bson.Document> list = new ArrayList<>();
// 获取集合中全部索引信息
for (org.bson.Document document : indexList) {
list.add(document);
}
return list.toString();
}
@ResponseBody
@RequestMapping("/removeindex")
public String removeIndex() { // 删除集合中某个索引
// 设置索引名称
String indexName = "username_1";
// 删除集合中某个索引
mongoTemplate.getCollection("test2").dropIndex(indexName);
return "已删除。";
}
@ResponseBody
@RequestMapping("/removeindexall")
public String removeIndexAll() { // 删除集合中全部索引
// 删除集合中全部索引
mongoTemplate.getCollection("test2").dropIndexes();
return "已删除全部索引。";
}
@ResponseBody
@RequestMapping("/createview")
public Object createView() { // 创建视图
// 设置视图名
String newViewName = "userView";
// 设置获取数据的集合名称
String collectionName = "test2";
// 定义视图的管道,可是设置视图显示的内容多个筛选条件
List<Bson> pipeline = new ArrayList<>();
// 设置条件,用于筛选集合中的文档数据,只有符合条件的才会映射到视图中
pipeline.add(Document.parse("{$match:{username:'admin'}}"));
// 执行创建视图
mongoTemplate.getDb().createView(newViewName, collectionName, pipeline);
// 检测新的集合是否存在,返回创建结果
return mongoTemplate.collectionExists(newViewName) ? "创建视图成功" : "创建视图失败";
}
@ResponseBody
@RequestMapping("/delall2")
public String dropCollection2() { //之前的 dropCollection() 方法 删除【集合】,其实也可以删除【视图】
// 设置集合名称
String collectionName = "userView";
// 执行删除集合
mongoTemplate.getCollection(collectionName).drop();
// 检测新的集合是否存在,返回删除结果
return !mongoTemplate.collectionExists(collectionName) ? "删除视图成功" : "删除视图失败";
}
@ResponseBody
@RequestMapping("/dropview")
public Object dropView() { //删除视图,也可以是集合
// 设置待删除的视图名称
String viewName = "test2";
// 检测视图是否存在
if (mongoTemplate.collectionExists(viewName)) {
// 删除视图
mongoTemplate.getDb().getCollection(viewName).drop();
return "删除视图成功";
}
// 检测新的集合是否存在,返回创建结果
return !mongoTemplate.collectionExists(viewName) ? "该视图不存在" : "删除视图失败";
}
@ResponseBody
@RequestMapping("/find3")
public String findByOperator() { // 根据【逻辑运算符】查询集合中的文档数据
// 设置查询条件参数
int min = 4;
int max = 8;
// 创建条件对象
Criteria criteria = Criteria.where("age").gt(min).lte(max);//大于4或小于等于8
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 查询并返回结果
List<User> documentList = mongoTemplate.find(query, User.class, "test2");
return documentList.toString();
}
}
User.java
package com.laisc.example4.entity;
public class User {
private Integer id = null;
private String username= "";
private String password= "";
private Integer age = 0;
private String role= "";
public User() {
}
public User(Integer id, String username, String password, Integer age, String role) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.role = role;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", role='" + role + '\'' +
'}';
}
}
项目源代码下载:https://pan.baidu.com/s/11rZQUp6MOjPhCHQEvyWCwg?pwd=63mi
上一篇:SpringBoot使用MyBatis连接MySQL:https://laisc7301.github.io/blog/2024/01/07/202401070000SpringBoot%E4%BD%BF%E7%94%A8MyBatis%E8%BF%9E%E6%8E%A5MySQL/
下一篇:SpringBoot使用Redis:https://laisc7301.github.io/blog/2024/01/21/202401210000SpringBoot%E4%BD%BF%E7%94%A8Redis/
原文:https://laisc7301.github.io/blog/2024/01/12/202401120000SpringBoot%E4%BD%BF%E7%94%A8MongoDB/