资讯详情 使用spring-data-mongodb操作mongo记录
📅 2026/10/22 13:02:00
目录一、 使用mongoTemplate操作3步骤新增批量新增修改删除更新查询分页查询二、使用 MongoRepository操作4步骤新增删除修改查询分页查询spring-data-mongodb提供了MongoTemplate与MongoRepository两种方式访问mongodbMongoRepository操作简单MongoTemplate操作灵活我们在项目中可以灵活适用这两种方式操作mongodbMongoRepository的缺点是不够灵活MongoTemplate正好可以弥补不足。1、使用MongoTemplate2、使用MongoRepository一、 使用mongoTemplate操作3步骤1.引入starter依赖dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-data-mongodb/artifactId /dependency2.配置文件yaml增加mongodb连接信息spring.mongodb.urimongodb://8.160.170.126:27018/test3.在使用的地方直接注入MongoTemplate对象Autowired private MongoTemplate mongoTemplate;创建一个对象// 添加lombok依赖 /*dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId /dependency */ Data NoArgsConstructor AllArgsConstructor //pojo类对应的集合(首字母小写): //Document(value Actor) public class Actor { // Id //当前属性和mongodb集合中的主键是对应的 // private String aaaid; //id 对应mongodb中集合的_id字段有一个对应关系:mongotemplate private String id; private String actorName; private Boolean gender; private Date birth; }新增新建测试类引入mongoTemplate新增可以使用save或 insertSpringBootTest // 和启动类同包可以不加classes属性(classes MongoDemoApplication.class) public class TemplateTest{ Autowired private MongoTemplate mongoTemplate; Test public void testInsert() { // mongoTemplate.insert(new Actor(3,刘德华insert,true,new Date())); Actor actor new Actor(); actor.setId(1); actor.setActorName(刘德华); mongoTemplate.save(actor); } }批量新增Test public void testBatchInsert() { ListActor actors new ArrayListActor(); actors.add(new Actor(11, Jerry, false, new Date())); actors.add(new Actor(13, Andy, false, new Date())); actors.add(new Actor(14, jack, false, new Date())); actors.add(new Actor(15, Tom, false, new Date())); mongoTemplate.insert(actors, Actor.class); }修改#新增可以使用insert、save方法1、insert只能做添加不能做修改,可以批量添加数据2、save既可以做添加也可以做修改,如果我们要使用save修改集合中某个字段的值其它字段保持原来的值必须是先查询出来然后修改最后写回去。Test public void testModify(){ Actor actor mongoTemplate.findById(3, Actor.class); actor.setActorName(刘德华insert_modiyf); mongoTemplate.save(actor); }删除# 删除:and 关系 Criteria.where(gender).is(false).and(actorName).is(张敏)# or关系: Criteria criterianew Criteria(); criteria.orOperator(Criteria2,Criteria2,...)Test public void testDelete(){ Criteria criterianew Criteria(); criteria.orOperator(Criteria.where(_id).is(1),Criteria.where(actorName).is(关之琳)); Query querynew Query(criteria); DeleteResult remove mongoTemplate.remove(query, Actor.class); System.out.println(remove.getDeletedCount()); // 打印删除个数 }更新Test public void testUpdate() { Query query new Query(Criteria.where(gender).is(true)); Update update new Update(); // 增加年龄字段 为 19 update.set(age, 19); // mongoTemplate.upsert(query, update, Actor.class); // mongoTemplate.updateFirst(query, update, Actor.class); mongoTemplate.updateMulti(query, update, Actor.class); }查询Test public void testQuery(){ // Actor actor mongoTemplate.findById(15, Actor.class); // System.out.println(actor); // // ListActor all mongoTemplate.findAll(Actor.class); // for (Actor actor1 : all) { // System.out.println(actor1); // } // Query querynew Query(Criteria.where(age).is(19)); // ListActor actors mongoTemplate.find(query, Actor.class); // for (Actor actor : actors) { // System.out.println(actor); // } String result String.format(%s%s%s, .*, j, .*); Pattern patternPattern.compile(result,Pattern.CASE_INSENSITIVE); Query querynew Query(Criteria.where(actorName).regex(pattern)); ListActor actors mongoTemplate.find(query, Actor.class); for (Actor actor : actors) { System.out.println(actor); } }分页查询//分页查询 Test public void testQueryPage() { int pageNum 1; int size 3; Query query new Query(Criteria.where(gender).is(false)); long total mongoTemplate.count(query, Actor.class); ListActor actors mongoTemplate.find(query.skip((pageNum - 1) * size).limit(size), Actor.class); for (Actor actor : actors) { System.out.println(actor); } MapString, Object map new HashMapString, Object(); map.put(total, total); map.put(rows, actors); System.out.println(total); }二、使用 MongoRepository操作4步骤1、导入starter依赖2、配置文件增加mong连接配置3、使用xxxRepository继承 MongoRepository实体对象主键类型public interface ActorRepository extends MongoRepositoryActor,String4、在使用的地方注入代理对象ActorRepository新增Test public void testInsert(){ // actorRepository.insert(new Actor(16,repos 1,true,new Date())); // actorRepository.save(new Actor(17,repos 2,true,new Date())); ListActor actorListnew ArrayListActor(); actorList.add(new Actor(40,周润发2,true,new Date())); actorList.add(new Actor(41,周星驰2,true,new Date())); actorList.add(new Actor(42,李连杰2,true,new Date())); // actorRepository.insert(actorList); actorRepository.saveAll(actorList); }删除Test public void testDelete(){ // actorRepository.deleteById(6ad88ab9dee946d789218d2b); Actor actor new Actor(); actor.setId(32); actorRepository.delete(actor); }修改Test public void testUpdate(){ Actor actornew Actor(); actor.setId(31); actor.setActorName(刘德华modify); actorRepository.save(actor); }查询Test public void testQuery(){ // Actor actor actorRepository.findById(30).get(); // System.out.println(actor); Actor actornew Actor(); //actor.setGender(true); actor.setActorName(j); ExampleMatcher matcher ExampleMatcher.matching() //构建对象 //.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式模糊查询 .withMatcher(actorName, ExampleMatcher.GenericPropertyMatchers.startsWith()) .withIgnoreCase(false); //改变默认大小写忽略方式忽略大小写 ExampleActor exampleExample.of(actor,matcher); ListActor all actorRepository.findAll(example); for (Actor actor1 : all) { System.out.println(actor1); } }分页查询Test public void testPage() { int pageNum 0; // 起始页从0开始 int pagesize 3; Actor actor new Actor(); actor.setGender(true); ExampleActor example Example.of(actor); // Pageable pageable PageRequest.of(pageNum,pagesize, Sort.by(id).descending()); Pageable pageable PageRequest.of(pageNum, pagesize); PageActor page actorRepository.findAll(example, pageable); System.out.println(总记录数 page.getTotalElements()); System.out.println(总页数 page.getTotalPages()); System.out.println(当前页列表数据); for (Actor actor1 : page.getContent()) { System.out.println(actor1); } }注意构建的分页对象起始页从0开始