查询:
1.or查询(前端输入一个字段,从后台两个字段中精确查询数据)
Criteria ca = new Criteria();
ca.orOperator(Criteria.where("roomCode").is(passengerInfo.getVisitRoomNum()),Criteria.where("visitRoomNum").is(passengerInfo.getVisitRoomNum()));
例:
Criteria ca = new Criteria();if (passengerInfo.getRoomCode() != null) {ca.and("roomCode").is(passengerInfo.getRoomCode());} else {ca.orOperator(Criteria.where("roomCode").is(passengerInfo.getVisitRoomNum()),Criteria.where("visitRoomNum").is(passengerInfo.getVisitRoomNum()));}ca.and("isDelete").is(BaseConstant.IS_NOT_DELETE);Query qu = new Query(ca);PassengerInfo info = mongoTemplate.findOne(qu, PassengerInfo.class);
2.时间区间查询
Date addEndTime = DateUtils.addDateDays(dto.getLeaveBeginTime(), 1);criteria.andOperator(Criteria.where("departureTime").gte(dto.getLeaveBeginTime()),Criteria.where("departureTime").lt(addEndTime));
3.模糊查询
Pattern pattern = Pattern.compile("^.*" + dto.getVisitName() + ".*$", Pattern.CASE_INSENSITIVE);criteria.and("visitName").regex(pattern);
4.模糊匹配(前端输入一个字段,从后台两个字段中模糊查询数据)
Pattern pattern = Pattern.compile("^.*" + dto.getEnglishName() + ".*$", Pattern.CASE_INSENSITIVE);
criteria.orOperator(Criteria.where("lastName").regex(pattern),
Criteria.where("surname").regex(pattern));
5.聚合查询、排序、分页、精确搜索
List<AggregationOperation> operations = new ArrayList<>();
Criteria criteria = new Criteria();
criteria.and("documentType").is(dto.getDocumentType());
operations.add(Aggregation.match(criteria));
operations.add(Aggregation.sort(new Sort(Sort.Direction.DESC, "createTime")));
operations.add(Aggregation.skip(dto.getPageDTO().getPageNum() * dto.getPageDTO().getPageSize().longValue()));operations.add(Aggregation.limit(dto.getPageDTO().getPageSize()));
Aggregation aggregation = Aggregation.newAggregation(operations);log.info("aggregation:" + aggregation);
AggregationResults<PassengerInfoVO> results = mongoTemplate.aggregate(aggregation, BaseConstant.CONNECTION_NAME, PassengerInfoVO.class);
增:
Collection<PassengerInfo> list = mongoTemplate.insert(passengerInfos, PassengerInfo.class);
改:
1.批量修改:先查询符合条件的数据,然后将符合条件的数据批量更新
Criteria cc = Criteria.where("visitRoomNum").is(passengerInfo.getRoomCode()).and("visitName").is(passengerInfo.getName()).and("hotelUid").is(passengerInfo.getHotelUid());Query qu = new Query(cc);log.info("qu:" + qu);List<PassengerInfo> list = mongoTemplate.find(qu, PassengerInfo.class);Update u = new Update();u.set("orderNum", passengerInfo.getOrderNum()).set("visitRoomNum", changRoomDTO.getRoomCode());BulkOperations ops = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, PassengerInfo.class);BulkOperations bulkOperations = ops.updateMulti(qu, u);BulkWriteResult execute = bulkOperations.execute();
2.只更新查询符合条件数据的第一条
Update update = new Update().set("isChangRoom", BaseConstant.IS_CHANG_ROOM).set("departureTime", new Date());UpdateResult updateResult = mongoTemplate.updateFirst(query, update, PassengerInfo.class);