SpringBoot使用MongoTemplate操作MongoDB数据库

1.新增一条数据。

template.save(answer);

直接调用save方法,answer是实体类对象。
存储之后,集合的名字就是answer实体类的名字首字母小写。

2.指定条件,修改一条信息

		//修改问答已采纳状态
        query=new Query(Criteria.where("_id").is(answerId));
        update= new Update();
        update.set("updateTime", new Date());
        update.set("isAdopt", AnswerIsAdoptEnum.ADOPT.getCode());
        //更新查询返回结果集的第一条
        result =template.updateFirst(query, update, MongoAnswer.class);

多个条件在query=new Query(Criteria.where("_id").is(answerId).and("").is(""));
多个更新的字段用update.set(ket, value)即可。

3.指定条件,指定字段增加操作。

//若是一级回答,则问题的回答数加一
        Query query=new Query(Criteria.where("_id").is(answer.getSuperId()));
        Update update= new Update().inc("answerCount", 1);
        update.set("updateTime", new Date());
        //更新查询返回结果集的第一条
        UpdateResult result =template.updateFirst(query,update, MongoProblem.class);

被指定增加操作的字段在mongodb数据库中必须是数值类型。

4.根据id查询列表。

		//根据问题id获取一级回答列表
        Criteria criatira = new Criteria();
        criatira.andOperator(Criteria.where("superId").is(superId));
        Query query=new Query(criatira);
        query.with(pageable);
        return template.find(query , MongoAnswer.class);

这里的pageable是传入的分页对象。
和SQL语句 SELECT * FROM mongoAnser WHERE superId = #{superId};等效

5.根据条件查询,返回数据条数。

		Criteria criatira = new Criteria();
        criatira.andOperator(Criteria.where("superId").is(problemId));
        Query query=new Query(criatira);
        //查询出一共的条数
        Long count =  template.count(query, MongoAnswer.class);

和SQL语句 SELECT count(*) FROM mongoAnser WHERE superId = #{problemId};等效

6.根据条件查询返回制定字段。

		//查询是否有别的回答被采纳过
        Document queryObject = new Document();
        queryObject.put("_id", problemId);
        Document fieldsObject=new Document();
        fieldsObject.put("isSolve", 1);

        Query query=new BasicQuery(queryObject, fieldsObject);
        MongoProblem problem = template.findOne(query , MongoProblem.class);

qyerObject 是查询条件,如果不需要,也要创建对象。
如果多个条件,执行多次执行queryObject.put(“属性名”,值);即可。
fieldsObject是指定返回的字段,如果不需要,也必须创建对象。
把需要的字段置为1,不需要的字段置为零。

7.分页及排序

		//排序
		Sort sort = new Sort(Sort.Direction.DESC,"createTime");
		//分页
        Pageable pageable =PageRequest.of(page, size);
        query.with(pageable);
        query.with(sort);

Sort对象的构造函数,第一个参数是 正序还是倒序,第二个参数是根据哪个字段排序。
可自行封装

8.查询list包含指定数据

		Document queryObject = new Document();
        List list = new ArrayList();
        list .add("http://meap-imgs.smarts.online/FvwBlgLVOeGS9snnQCXtnABHrkxW");
        
        queryObject.put("problemImgList", new BasicDBObject("$in", list ));
        Document fieldsObject = new Document();

        Query query = new BasicQuery(queryObject, fieldsObject);

        List<MongoProblem> mongoAnswerList = template.find(query, MongoProblem.class);

使用条件操作符 $in $all

你可能感兴趣的:(数据库)