需求:
1、获取保存到mongodb库中的搜索记录列表
2、实现删除搜索记录接口
保存搜索记录数据参考上篇Mongodb:业务应用(1)_Success___的博客-CSDN博客
获取记录列表
1、创建controller
package com.heima.search.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.search.service.ArticleSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/history")
public class SearchHistoryController {
    
    @Autowired
    ArticleSearchService articleSearchService;
    @PostMapping("/load")
    public ResponseResult getHistory(){
        return articleSearchService.getHistory();
    }
}
 
2、service实现类
    /**
     查询搜索历史
     @return
     */
    @Override
    public ResponseResult getHistory() {
        
        //查询当前用户下面的搜索记录
        Integer userId = AppThreadLocalUtil.getUser().getId();
        //构造条件
        Query query = Query.query(Criteria.where("userId").is(userId));
        //执行查询
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        //返回数据
        return ResponseResult.okResult(list);
    } 
3、测试
返回成功

根据id删除搜索记录
1、实现controller
    @PostMapping("/del")
    public ResponseResult delHistory(@RequestBody ApUserSearch userSearch){
        return articleSearchService.del(userSearch);
    } 
2、service实现类
    /*根据id删除搜索记录*/
    @Override
    public ResponseResult del(HistorySearchDto dto) {
        //检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //检查登录状态
        Integer userId = AppThreadLocalUtil.getUser().getId();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //执行删除
        mongoTemplate.remove(Query.query(Criteria.where("userId")
                .is(userId).and("id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    } 
3、测试



![[Idea热部署]两秒钟学会热部署](https://img-blog.csdnimg.cn/417aa759f02949c5bcf30575fd8a8b19.png)















