/** * Creates a group operation by specified field with sum of contentFields values * * @param field Grouping field * @param contentFields Fields for summing * @return Group operation */ private GroupOperation groupByFieldWithStatisticsSumming(String field, List<String> contentFields) { GroupOperation groupOperation = Aggregation.group(field); for (String contentField : contentFields) { groupOperation = groupOperation.sum(contentField).as(contentField.replace('.', '$')); } return groupOperation; }
@Cacheable(value = { CacheConfiguration.PROJECT_INFO_CACHE }) @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Map<String, Integer> findGroupedLaunchesByOwner(String projectName, String mode, Date from) { Map<String, Integer> output = new HashMap<>(); Aggregation aggregation = newAggregation(match(where(PROJECT_ID_REFERENCE).is(projectName)), match(where(MODE).is(mode)), match(where(STATUS).ne(IN_PROGRESS.name())), match(where(START_TIME).gt(from)), group("$userRef").count().as("count") ); AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, Launch.class, Map.class); for (Map<String, String> entry : result.getMappedResults()) { String username = entry.get("_id"); String count = String.valueOf(entry.get("count")); output.put(username, Integer.valueOf(count)); } return output; }
/** * 按照日期获取tx的数量 * * @return */ @Override public Map<String, String> clientDetails(Boolean source) { Map<String, String> res = new HashMap<>(); String attr = source ? "source" : "target"; Arrays.stream(ServiceNameEnum.values()).forEach(serviceNameEnum -> { String service = serviceNameEnum.getServiceName(); Aggregation aggregation = Aggregation.newAggregation( match(new Criteria(attr).is(service)), group(attr).count().as("count") ); AggregationResults<BasicDBObject> results = mongoTemplate.aggregate(aggregation, CollectionNameEnum.TransactionMsg.name(), BasicDBObject.class); List<BasicDBObject> dbObjects = results.getMappedResults(); for (int i = 0; i < dbObjects.size(); i++) { BasicDBObject data = dbObjects.get(i); res.put(data.getString("_id"), data.getString("count")); } }); return res; }
@Override public long getPageNumber(String entityId, Queryable filterable, Pageable pageable) { ImmutableList.Builder<AggregationOperation> pipelineBuilder = ImmutableList.<AggregationOperation>builder() .add(matchOperationFromFilter(filterable, mongoOperations, this.getEntityInformation().getJavaType())); if (null != pageable.getSort()){ pipelineBuilder.add( /* sort results as requested */ sort(pageable.getSort()) ); } pipelineBuilder.add( /* group items into one field pushing all results into one array */ group("result").push("$_id").as("array"), /* unwind array adding index to each result */ unwind("array", "ind", false), /* find needed item. How we know its index in query result */ match(where("array").is(ObjectId.isValid(entityId) ? new ObjectId(entityId) : entityId)), /* grab index only */ project("ind")); /* find items matching an provided filter */ Aggregation a = Aggregation .newAggregation(toArray(pipelineBuilder.build(), AggregationOperation.class)); final AggregationResults<Map> aggregate = mongoOperations.aggregate( a, getEntityInformation().getCollectionName(), Map.class); if (!aggregate.getUniqueMappedResult().containsKey("ind")) { throw new ReportPortalException(ErrorType.INCORRECT_FILTER_PARAMETERS, "Unable to calculate page number. Check your input parameters"); } /* result returned as long. Calculate page number */ return (long) Math.ceil ((((Long) aggregate.getUniqueMappedResult().get("ind")).doubleValue() + 1d) / (double) pageable.getPageSize()); }
("project", "$_id") .append("projectRole", "$users.projectRole")) .as("projects"), lookup("user", "_id", "_id", "user") );
GroupOperation groupOperation = Aggregation.group("appName", "execDate").count().as("count");
@Override public BaseResponse getErrorLogGroupByAppName() throws BaseException { //查询条件信息 Criteria operator = new Criteria(); operator.andOperator( //查询当天的数据汇总 Criteria.where("execDate").is(DateUtil.today()) ); //查询条件 MatchOperation matchOperation = Aggregation.match(operator); //分组信息及返回count列命名 GroupOperation groupOperation = Aggregation.group("serUrl", "serPort", "appName", "appSer", "reqUrl", "execDate").count().as("count"); //排序信息 Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "count")); SortOperation sortOperation = Aggregation.sort(sort); //组合条件 Aggregation aggregation = Aggregation.newAggregation(ErrorInfo.class, matchOperation, groupOperation, sortOperation); // 执行操作 AggregationResults<Map> aggregationResults = template.aggregate(aggregation, ErrorInfo.class, Map.class); return new BaseResponse(aggregationResults.getMappedResults()); }
@Override public List<RetryObject> findRetries(String launchId) { Aggregation aggregation = newAggregation(match(where(LAUNCH_REFERENCE).is(launchId).and("retryProcessed").exists(true)), sort(new Sort(Sort.Direction.ASC, "start_time")), group(Fields.fields("$uniqueId")).push(ROOT).as("retries") ); return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(TestItem.class), RetryObject.class).getMappedResults(); }
private GroupOperation mostFailedGroup(String criteria) { final String CRITERIA = "$" + criteria; return group(Fields.fields("$uniqueId")).count() .as(TOTAL) .first("$name") .as(NAME) .push(new BasicDBObject(START_TIME, "$start_time").append("criteriaAmount", CRITERIA)) .as("statusHistory") .sum(CRITERIA) .as(FAILED); }
private List<AggregationOperation> latestLaunchesAggregationOperationsList(Queryable filter) { return Lists.newArrayList(matchOperationFromFilter(filter, mongoTemplate, Launch.class), sort(DESC, NUMBER), group("$name").first(ROOT).as(ORIGINAL), replaceRoot(ORIGINAL) ); }
public List<ServiceCount> countServicesByType() { Aggregation aggregation = newAggregation( project("type"), group("type").count().as("number"), project("number").and("type").previousOperation(), sort(DESC, "number") ); AggregationResults<ServiceCount> results = template.aggregate(aggregation, Service.class, ServiceCount.class); return results.getMappedResults(); } }
@Override public List<InvocationCount> aggregateDailyStatistics(String afterday, String beforeday) { // Build a query to pre-select the statistics that will be aggregated. Aggregation aggregation = newAggregation( match(Criteria.where("day").gte(afterday).lte(beforeday)), group("day").sum("dailyCount").as("number"), project("number").and("day").previousOperation(), sort(ASC, "day") ); AggregationResults<InvocationCount> results = template.aggregate(aggregation, DailyStatistic.class, InvocationCount.class); return results.getMappedResults(); }
/** * The implementation uses the MongoDB aggregation framework support Spring Data provides as well as SpEL expressions * to define arithmetical expressions. Note how we work with property names only and don't have to mitigate the nested * {@code $_id} fields MongoDB usually requires. * * @see example.springdata.mongodb.aggregation.OrderRepositoryCustom#getInvoiceFor(example.springdata.mongodb.aggregation.Order) */ @Override public Invoice getInvoiceFor(Order order) { AggregationResults<Invoice> results = operations.aggregate(newAggregation(Order.class, // match(where("id").is(order.getId())), // unwind("items"), // project("id", "customerId", "items") // .andExpression("'$items.price' * '$items.quantity'").as("lineTotal"), // group("id") // .sum("lineTotal").as("netAmount") // .addToSet("items").as("items"), // project("id", "items", "netAmount") // .and("orderId").previousOperation() // .andExpression("netAmount * [0]", taxRate).as("taxAmount") // .andExpression("netAmount * (1 + [0])", taxRate).as("totalAmount") // ), Invoice.class); return results.getUniqueMappedResult(); } }