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