查询结果
只显示部分返回字段
例如,使用的返回类里面有多个参数,但是只用到其中两三个,使用query.fields().include(field) 方法,查询只返回需要的字段。具体使用方法如下:
//需要查询的字段名称,用逗号隔开
String fields = "_id, name,patientId";
Query query = new Query();
//分割需要查询的字段
String[] splitFields = fields.split(",");
Assert.notEmpty(splitFields, "fields must not be null!");
//将字段列表转换为数据流
Stream<String> stream = Arrays.stream(splitFields);
//将需要的字段传入query条件中, .trim 为去除空格的方法
stream.forEach(field -> query.fields().include(field.trim()));
同样,要排除字段的查询,可以用 query.fields().exclude(field)方法
在MongoUtil类下有几个
例子:include限制显示指定字段
Query query = new Query();
query.addCriteria(Criteria.where("isException").is(0));
//此处“1000”为不同订单id
query.addCriteria(Criteria.where("patient.pid").in(CurrentUserHelper.getUserId(), "1000"));
query.addCriteria(Criteria.where("patient.patientId").in(patientIds));
query.addCriteria(Criteria.where("createAt").lt(DateUtil.toISODate(createTime)));
query.limit(15);
query.with(Sort.by(Sort.Order.desc("createAt")));
MongoUtil.include(query, "_id,patient.name,patient.mobile,type,patient.gender,orderStatus,amount,useCoupon," +
"orderAmount,coupon, actualdAmount,createAt");
repository.findBy(query, OrderVo.class);
查询条件
聚合查询
聚合方法类:List<AggregationOperation>
构建聚合管道
//构造聚合管道操作
List<AggregationOperation> operationList = new ArrayList<>();
Criteria criteria = new Criteria();
criteria.and("_id").is(id);
MatchOperation match = Aggregation.match(criteria);
operationList.add(match);//定义第一个操作 设置查询条件 指定id
UnwindOperation unwind = Aggregation.unwind("projects");
operationList.add(unwind);//定义第二个操作 设展开字段projects
GroupOperation groupOperation = Aggregation.group("projects");
operationList.add(groupOperation);//定义第三个操作 设置分组字段projects
ProjectionOperation projection = Aggregation.project("_id")
.and("_id.code").as("c")
.and("_id.laboratory.name").as("ln")
.and("_id.sampleCode").as("sc")
.and("_id.vouchers").as("v")
.and("_id.forms").as("f");
operationList.add(projection);//定义第三个操作 设置查询得到的字段的简称
Aggregation aggregation = Aggregation.newAggregation(operationList);
List<OrderProjectVo> list =
repository.getMongoOps().aggregate(aggregation, "orders", OrderProjectVo.class).getMappedResults();
操作
事务化
注解@transactional
增删改操作都需要事务化注解,注解属性见http://t.csdnimg.cn/dncy8
例子:
/**
* 新增项目
*/
@Transactional(timeout = 3, rollbackFor = Exception.class)
public Item create(Item item) {
Item newItem = itemRepository.save(item);
if (Objects.nonNull(newItem)) {
//分类下所属项目/套餐个数
newItem.getCategoryList().forEach(c -> {
if (!CollectionUtils.isEmpty(c.getSecCategoryList())) {
c.getSecCategoryList().forEach(sc -> {
categoryRepository.incChidrenNum(sc.getId());
});
}
});
//新增App端查询数据信息
Search search = Search.createItem(newItem);
searchRepository.save(search);
}
return newItem;
}