Mongodb中,实现类似以下查询的功能(分组和分页):
select distinct groupid, hcpID
from tableA
group by groupId
limit 0, 10
代码:
- @Override
- public Page<Demo> findHistoryPageList(Integer page, Integer size, String groupId, Long hcpId) {
- Criteria criteria = getCriteria(groupId);
- if (hcpId != null) {
- criteria.and(HCP_ID).is(hcpId);
- }
- Aggregation aggregation = Aggregation.newAggregation(
- CdccMedicalGroupInfo.class,
- Aggregation.match(criteria),
- Aggregation.group(GROUP_ID).first(GROUP_ID).as(GROUP_ID).first(HCP_ID).as(HCP_ID)
- );
- AggregationResults<Demo> results = mongoTemplate.aggregate(aggregation, Demo.class, Demo.class);
- List<Demo> groupIds = results.getMappedResults();
- int formIndex = page * size;
- int toIndex = Math.min((page + 1) * size, groupIds.size());
- if (formIndex > toIndex){
- formIndex = 0;
- toIndex = 0;
- }
- return new PageImpl<>(groupIds.subList(formIndex, toIndex), PageRequest.of(page, size), groupIds.size());
- }
如果要实现以下功能:
select count(*) as total from (
select groupid from
from tableA
group by groupId
)
代码如下:
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.mongodb.core.MongoTemplate;
- import org.springframework.stereotype.Service;
- import org.springframework.data.mongodb.core.aggregation.Aggregation;
- import org.springframework.data.mongodb.core.aggregation.AggregationResults;
- import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
- @Service
- public class TableAService {
- private final MongoTemplate mongoTemplate;
- @Autowired
- public TableAService(MongoTemplate mongoTemplate) {
- this.mongoTemplate = mongoTemplate;
- }
- public long getCountDistinctGroupId() {
- Aggregation aggregation = newAggregation(
- group("groupId"),
- group().count().as("count")
- );
- AggregationResults<CountResult> results = mongoTemplate.aggregate(
- aggregation, "tableA", CountResult.class
- );
- CountResult countResult = results.getUniqueMappedResult();
- if (countResult != null) {
- return countResult.getCount();
- } else {
- return 0L;
- }
- }
- }
- class CountResult {
- private long count;
- public long getCount() {
- return count;
- }
- public void setCount(long count) {
- this.count = count;
- }
- }
不使用实体类的写法:
- List<Map> totalResult = mongoTemplate.aggregate(
- Aggregation.newAggregation(
- Aggregation.match(criteria),
- Aggregation.group("groupID"),
- Aggregation.group("groupID").count().as("total")
- ),
- "TableA",
- Map.class
- ).getMappedResults();
- long total = Long.valueOf(totalResult.get(0).get("total").toString());