1、安裝依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>
2、配置數據庫連接
spring:data:mongodb:host: localhostport: 27017username: xxxxxxpassword: xxxxxxdatabase: xxxxxxauthentication-database: admin
3、新建實體類
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;@Data
//代表集合名稱
@Document("myCollection")
public class MyCollection {@Idprivate String id;private String name;private Integer age;private String sex;
}
4、調用方法
4.1 方法一
package com.example.springboot3test.controller;import com.example.springboot3test.entity.MyCollection;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
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.web.bind.annotation.*;import java.util.List;
import java.util.regex.Pattern;@RestController
@RequestMapping("/test")
public class TestController {@Resourceprivate MongoTemplate mongoTemplate;//引入的對象//查詢所有不帶條件@GetMapping("/findAllData")public List<MyCollection> findAllData(){return mongoTemplate.findAll(MyCollection.class);}//根據Id查詢@GetMapping("/findDataById/{id}")public MyCollection findDataById(@PathVariable("id") String id){return mongoTemplate.findById(id,MyCollection.class);}//where條件查詢@PostMapping("/findByWhere")public List<MyCollection> findByWhere(@RequestBody MyCollection myCollection){Query query=new Query(Criteria.where("name").is(myCollection.getName()).and("age").gte(myCollection.getAge()));return mongoTemplate.find(query,MyCollection.class);}//模糊查詢@PostMapping("/findByLike")public List<MyCollection> findByLike(@RequestBody MyCollection myCollection){String regex = String.format("%s%s%s", "^.*", myCollection.getName(), ".*$");Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);Query query=new Query(Criteria.where("name").regex(pattern));return mongoTemplate.find(query,MyCollection.class);}//插入@PostMapping("/insertMongodb")public String insertMongodb(@RequestBody MyCollection myCollection){mongoTemplate.insert(myCollection);return "OK";}//批量插入@PostMapping("/insertBatchsMongodb")public String insertBatchsMongodb(@RequestBody List<MyCollection> list){mongoTemplate.insertAll(list);return "OK";}//更新@PostMapping("/updateMongodb")public String updateMongodb(@RequestBody MyCollection myCollection){Query query=new Query(Criteria.where("age").gte(38));Update update=new Update();update.set("name",myCollection.getName());//單條更新//mongoTemplate.upsert(query,update,MyCollection.class);//批量更新mongoTemplate.updateMulti(query,update,MyCollection.class);return "OK";}//刪除根據條件@GetMapping("/deleteMongodb/{age}")public String deleteMongodb(@PathVariable("age") Long age){Query query=new Query(Criteria.where("age").gte(age));mongoTemplate.remove(query,MyCollection.class);return "OK";}
}
注:其中的常用方法如下
常用方法
mongoTemplate.findAll(User.class): 查詢User文檔的全部數據
mongoTemplate.findById(<id>, User.class): 查詢User文檔id為id的數據
mongoTemplate.find(query, User.class);: 根據query內的查詢條件查詢
mongoTemplate.upsert(query, update, User.class): 修改
mongoTemplate.remove(query, User.class): 刪除
mongoTemplate.insert(User): 新增Query對象
1、創建一個query對象(用來封裝所有條件對象),再創建一個criteria對象(用來構建條件)
2、 精準條件:criteria.and(“key”).is(“條件”)模糊條件:criteria.and(“key”).regex(“條件”)
3、封裝條件:query.addCriteria(criteria)
4、大于(創建新的criteria):Criteria gt = Criteria.where(“key”).gt(“條件”)小于(創建新的criteria):Criteria lt = Criteria.where(“key”).lt(“條件”)
5、Query.addCriteria(new Criteria().andOperator(gt,lt));
6、一個query中只能有一個andOperator()。其參數也可以是Criteria數組。
7、排序 :query.with(new Sort(Sort.Direction.ASC, "age"). and(new Sort(Sort.Direction.DESC, "date")))
Criteria查詢條件類常用方法
//聲明定義查詢條件,且為靜態方法
where(String key)
//與操作
and(String key)
//正則表達式,即可為模糊查詢
regex(String re)
//包含
in(Object... o)
//大于
gt(Object o)
//大于等于
gte(Object o)
//等于
is(Object o)
//小于
lt(Object o)
//小于等于
lte(Object o)
//非
not()
//創建與操作
andOperator(Criteria... criteria)
4.2 方法二 spring Data 方式
spring Data提供了對mongodb數據訪問的支持,我們只需要繼承MongoRepository類,按照Spring Data規范就可以了。
當需要根據實體類中的屬性查詢時,MongoRepository提供的方法已經不能滿足,我們需要在PersonRepository倉庫中定義方法,定義方法名的規則為:find + By + 屬性名(首字母大寫)
step1 新建MyCollectionRepository接口
package com.example.springboot3test.dao;import com.example.springboot3test.entity.MyCollection;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface MyCollectionRepository extends MongoRepository<MyCollection,String> {//當需要根據實體類中的屬性查詢時,MongoRepository提供的方法已經不能滿足,我們需要在PersonRepository倉庫中定義方法,定義方法名的規則為:find + By +// 屬性名(首字母大寫),如:根據姓名查詢Person。//倉庫中添加的方法//根據名稱查詢List<MyCollection> findByName(String name);//模糊查詢List<MyCollection> findByNameLike(String name);//模糊查詢List<MyCollection> findByNameLikeAndAgeGreaterThanEqual(String name,Integer age);}
step2 、測試代碼
package com.example.springboot3test.controller;import com.example.springboot3test.dao.MyCollectionRepository;
import com.example.springboot3test.entity.MyCollection;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/mongodb")
public class TestMongodbController {@Resourceprivate MyCollectionRepository myCollectionRepository;//插入單條@PostMapping("/insertMongodb")public String insertMongodb(@RequestBody MyCollection myCollection){myCollectionRepository.insert(myCollection);return "OK";}//批量插入@PostMapping("/insertMongodbBatchs")public String insertMongodbBatchs(@RequestBody List<MyCollection> myCollection){myCollectionRepository.insert(myCollection);return "OK";}//更新@PostMapping("/updateMongodb")public String updateMongodb(@RequestBody MyCollection myCollection){myCollectionRepository.save(myCollection);//myCollectionRepository.insert(myCollection);return "OK";}//刪除@GetMapping("/deleteMongodbById/{id}")public String deleteMongodbById(@PathVariable("id") String id){myCollectionRepository.deleteById(id);return "OK";}//查詢所有@GetMapping("/findAll")public List<MyCollection> findAll(){return myCollectionRepository.findAll();}//根據Id進行查詢@GetMapping("/findById/{id}")public MyCollection findById(@PathVariable("id") String id){return myCollectionRepository.findById(id).get();}//條件查詢@PostMapping("/findQuery")public List<MyCollection> findQuery(@RequestBody MyCollection myCollection){//Example<MyCollection> example=Example.of(myCollection);return myCollectionRepository.findByName(myCollection.getName());}//模糊匹配@PostMapping("/findLike")public List<MyCollection> findLike(@RequestBody MyCollection myCollection){
// ExampleMatcher matcher = ExampleMatcher.matching() //構建對象
// .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改變默認字符串匹配方式:模糊查詢
// .withIgnoreCase(true);//改變默認大小寫忽略方式:忽略大小寫
// Example<MyCollection> example=Example.of(myCollection,matcher);return myCollectionRepository.findByNameLike(myCollection.getName());//單個模糊查詢}//模糊匹配@PostMapping("/findLikeAnd")public List<MyCollection> findLikeAnd(@RequestBody MyCollection myCollection){
// ExampleMatcher matcher = ExampleMatcher.matching() //構建對象
// .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改變默認字符串匹配方式:模糊查詢
// .withIgnoreCase(true);//改變默認大小寫忽略方式:忽略大小寫
// Example<MyCollection> example=Example.of(myCollection,matcher);//多個條件模糊查詢return myCollectionRepository.findByNameLikeAndAgeGreaterThanEqual(myCollection.getName(),myCollection.getAge());}}