Spring boot集成mongodb 简单运用示例 (Mongodb快速入门)
一.安装
1.选取社区版,windows系统,mongodb版本根据你的电脑配置
#管理员权限cmd
net start MongoDB
2.Docker容器安装
#拉取镜像
docker pull mongo:latest
#创建和启动容器
docker run -d --restart=always -p 27017:27017 --name mymongo -v /data/db:/data/db -d mongo
#进入容器
docker exec -it mymongo/bin/bash
二.Spring boot集成mongodb
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
2.配置
spring.data.mongodb.uri=mongodb://xxx.xxx.xxx.xxx:27017/mongdbTest
3.CRUD示例
(1)MongoTemplate
package com.kino.study.mongodb;
import com.kino.study.mongodb.entity.User;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.util.List;
import java.util.regex.Pattern;
@SpringBootTest
class MongodbApplicationTests {
@Autowired
MongoTemplate mongoTemplate;
// 添加
@Test
void add() {
User wdd = mongoTemplate.insert(new User().setAge(18)
// .setCreateDate(LocalDateTime.now().toString())
.setName("wdd")
.setEmail("77777@qqq.com"));
System.out.println(wdd);
}
// 查询操作
@Test
void findAll() {
List<User> all = mongoTemplate.findAll(User.class);
System.out.println(all);
}
// 根据id查询操作
@Test
void findById() {
User user = mongoTemplate.findById("61b498c588583433191dafd5", User.class);
System.out.println(user);
}
// 条件查询操作
@Test
void findUserList() {
Query query = Query.query(Criteria.where("name").is("wdd").and("age").is(18));
List<User> users = mongoTemplate.find(query, User.class);
System.out.println(users);
}
// 模糊查询操作
@Test
void findLikeUserList() {
String regex = String.format("%s%s%s", "^.*", "wd", ".*$");
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Query query = Query.query(Criteria.where("name").regex(pattern));
List<User> users = mongoTemplate.find(query, User.class);
System.out.println(users);
}
// 分页查询操作
@Test
void findPageUserList() {
int current = 1;
int pageSize = 3;
String regex = String.format("%s%s%s", "^.*", "wd", ".*$");
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Query query = Query.query(Criteria.where("name").regex(pattern));
long count = mongoTemplate.count(query, User.class);
// 分页
List<User> users = mongoTemplate.find(query.skip((current - 1) * pageSize).limit(pageSize), User.class);
System.out.println(users);
System.out.println(count);
}
// 修改
@Test
void updateUser() {
// 根据id查询
User user = mongoTemplate.findById("61b498c588583433191dafd5", User.class);
// 设置修改值
user.setName("wzz");
user.setAge(19);
user.setEmail("100000@qqq.com");
// mongoTemplate.save(user);
Query query = Query.query(Criteria.where("_id").is(user.getId()));
Update update = Update.update("name", user.getName());
update.set("age", user.getAge()).set("email", user.getEmail());
// Update name = Update.update("name", user.getName());
UpdateResult result = mongoTemplate.upsert(query, update, User.class);
long modifiedCount = result.getModifiedCount();
System.out.println(modifiedCount);
}
// 删除
@Test
void deleteUser() {
Query query = new Query(Criteria.where("_id").is("61b498c588583433191dafd5"));
DeleteResult result = mongoTemplate.remove(query, User.class);
long count = result.getDeletedCount();
System.out.println(count);
}
}
(2)MongoRepository
实际项目可结合Spring Data对mongodb的支持
package com.kino.study.mongodb.mapper;
import com.kino.study.mongodb.entity.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends MongoRepository<User, String> {
}
package com.kino.study.mongodb;
import com.kino.study.mongodb.entity.User;
import com.kino.study.mongodb.mapper.UserMapper;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
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 java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
@SpringBootTest
class MongoRepositoryTests {
@Autowired
UserMapper userMapper;
// 添加操作
@Test
void insert() {
User kino = userMapper.insert(new User().setAge(18)
// .setCreateDate(LocalDateTime.now().toString())
.setName("kino")
.setEmail("7222227777@qqq.com"));
System.out.println(kino);
}
// 查询操作
@Test
void findAll() {
List<User> all = userMapper.findAll();
System.out.println(all);
}
// 根据id查询操作
@Test
void findById() {
Optional<User> optional = userMapper.findById("61b49942a049790b9fae7a12");
optional.ifPresent(System.out :: println);
}
// 条件查询操作
@Test
void findUserList() {
// name, email
Example<User> userExample = Example.of(new User().setAge(18)
.setName("kino")
.setEmail("7222227777@qqq.com"));
List<User> userList = userMapper.findAll(userExample);
System.out.println(userList);
}
// 模糊查询操作
@Test
void findLikeUserList() {
User user = new User().setAge(18)
.setName("ki");
// 匹配规则
ExampleMatcher matcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase();
Example<User> userExample = Example.of(user, matcher);
List<User> users = userMapper.findAll(userExample);
System.out.println(users);
}
// 分页查询操作
@Test
void findPageUserList() {
Example<User> userExample = Example.of(new User().setAge(18)
.setName("kino")
.setEmail("7222227777@qqq.com"));
Pageable pageable = PageRequest.of(0, 5);
Page<User> userPage = userMapper.findAll(userExample, pageable);
System.out.println(userPage.getTotalElements());
System.out.println(userPage.getTotalPages());
System.out.println(userPage.getContent());
System.out.println(userPage);
}
// 修改
@Test
void updateUser() {
// 根据id查询
Optional<User> optionalUser = userMapper.findById("61b4b5d2d58e985207ebefb8");
optionalUser.ifPresent(user -> {
// 设置修改值
user.setName("wzz");
user.setAge(18);
user.setEmail("wzzzzzz@qqq.com");
User save = userMapper.save(user);
System.out.println(save);
});
}
// 删除
@Test
void deleteUser() {
boolean exist = userMapper.existsById("61b4b81567adc369627e57cb");
System.out.println(exist);
userMapper.deleteById("61b4b81567adc369627e57cb");
exist = userMapper.existsById("61b4b81567adc369627e57cb");
System.out.println(exist);
}
}
三.Mongodb
1.概念
1、文档中的键/值对是有序的。
2、文档中的值可以是多种数据类型
3、MongoDB区分类型和大小写。
4、MongoDB文档不能有重复的键。
5、文档的键是字符串。除了少数例外情况,键可以使用任意UTF-8字符
2.增删改查示例
(1)基础操作
- Help查看命令提示
db.help() - 切换/创建数据库
use test
如果数据库不存在,则创建数据库,否则切换到指定数据库 - 查询所有数据库
show dbs - 删除当前使用数据库
db.dropDatabase() - 查看当前使用的数据库
db.getName() - 显示当前db状态
db.stats() - 当前db版本
db.version() - 查看当前db的链接机器地址
db.getMongo()
(2)常用操作
- INSERT
db.User.save({name:‘wdd’,age:18})
db.User.find()