/** * 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(); } }
return new AggregationResults<>(commandResult.get("results", new ArrayList<Document>(0)).stream() .map(callback::doWith).collect(Collectors.toList()), commandResult); }); return new AggregationResults<>(iterable.into(new ArrayList<>()), new Document("results", rawResult).append("ok", 1.0D)); });
/** * Creates a new {@link AggregationResults} instance from the given mapped and raw results. * * @param mappedResults must not be {@literal null}. * @param rawResults must not be {@literal null}. */ public AggregationResults(List<T> mappedResults, Document rawResults) { Assert.notNull(mappedResults, "List of mapped results must not be null!"); Assert.notNull(rawResults, "Raw results must not be null!"); this.mappedResults = Collections.unmodifiableList(mappedResults); this.rawResults = rawResults; this.serverUsed = parseServerUsed(); }
@Override public List<String> findItemIdsByLaunchRef(List<String> launchRefs) { Aggregation aggregation = newAggregation(match(where(LAUNCH_REFERENCE).in(launchRefs)), group(ID_REFERENCE)); AggregationResults<Map> aggregationResults = mongoTemplate.aggregate(aggregation, TestItem.class, Map.class); return aggregationResults.getMappedResults().stream().map(it -> it.get("_id").toString()).collect(toList()); }
@Override public void findLatestWithCallback(Queryable filter, Sort sort, List<String> contentFields, long limit, DocumentCallbackHandler callbackHandler) { List<AggregationOperation> operations = latestLaunchesAggregationOperationsList(filter); operations.add(sort(sort)); operations.add(limit(limit)); DBObject results = mongoTemplate.aggregate(newAggregation(operations), mongoTemplate.getCollectionName(Launch.class), Launch.class) .getRawResults(); BasicDBList result = (BasicDBList) results.get(RESULT); result.stream().map(it -> (DBObject) it).forEach(callbackHandler::processDocument); }
@Override public List<String> findLogIdsByItemRefs(List<String> ids) { Aggregation aggregation = newAggregation(match(where("testItemRef").in(ids)), group("id")); AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, Log.class, Map.class); return results.getMappedResults().stream().map(it -> it.get("_id").toString()).collect(toList()); }
@Override public List<String> findLaunchIdsByProjectIds(List<String> ids) { Aggregation aggregation = newAggregation(match(where(PROJECT_ID_REFERENCE).in(ids)), group(ID_REFERENCE)); AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, Launch.class, Map.class); return results.getMappedResults().stream().map(it -> it.get("_id").toString()).collect(toList()); }
private Long countLatestLaunches(Queryable filter) { Long total = 0L; final String countKey = "count"; List<AggregationOperation> operations = latestLaunchesAggregationOperationsList(filter); operations.add(Aggregation.count().as(countKey)); Map result = mongoTemplate.aggregate(newAggregation(operations), Launch.class, Map.class).getUniqueMappedResult(); if (null != result && result.containsKey(countKey)) { total = Long.valueOf(result.get(countKey).toString()); } return total; }
/** * Creates a new {@link AggregationResults} instance from the given mapped and raw results. * * @param mappedResults must not be {@literal null}. * @param rawResults must not be {@literal null}. */ public AggregationResults(List<T> mappedResults, Document rawResults) { Assert.notNull(mappedResults, "List of mapped results must not be null!"); Assert.notNull(rawResults, "Raw results must not be null!"); this.mappedResults = Collections.unmodifiableList(mappedResults); this.rawResults = rawResults; this.serverUsed = parseServerUsed(); }
return new AggregationResults<>(commandResult.get("results", new ArrayList<Document>(0)).stream() .map(callback::doWith).collect(Collectors.toList()), commandResult); }); return new AggregationResults<>(iterable.into(new ArrayList<>()), new Document("results", rawResult).append("ok", 1.0D)); });
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override public List<String> getUniqueTicketsCount(List<Launch> launches) { List<String> launchIds = launches.stream().map(Launch::getId).collect(toList()); Aggregation aggregation = newAggregation(match(where(LAUNCH_REFERENCE).in(launchIds)), match(where(ISSUE_TICKET).exists(true)), unwind(ISSUE_TICKET), group(ISSUE_TICKET) ); // Count be as // Aggregation.group("issue.externalSystemIssues").count().as("count"); // but keep a whole AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, TestItem.class, Map.class); return result.getMappedResults().stream().map(entry -> entry.get("ticketId").toString()).collect(toList()); }
@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()); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override public List<String> findDistinctValues(String launchId, String containsValue, String distinctBy) { Aggregation aggregation = newAggregation(match(where(LAUNCH_REFERENCE).is(launchId)), unwind(distinctBy), match(where(distinctBy).regex("(?i).*" + Pattern.quote(containsValue) + ".*")), group(distinctBy) ); AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, TestItem.class, Map.class); return result.getMappedResults().stream().map(entry -> entry.get("_id").toString()).collect(toList()); }
); return mongoOperations.aggregate(a, mongoOperations.getCollectionName(Project.class), UserRoleDetails.class).getUniqueMappedResult();
@Override public List<String> findBinaryIdsByLogRefs(List<String> ids) { Aggregation aggregation = newAggregation(match(where("id").in(ids).andOperator(where("binaryContent").exists(true))), group("binaryContent.binaryDataId", "binaryContent.thumbnailId")); AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, Log.class, Map.class); return results.getMappedResults().stream().flatMap(it -> (Stream<String>) it.values().stream()).collect(toList()); }
@Override public List<String> findBinaryIdsByItemRefs(List<String> ids) { Aggregation aggregation = newAggregation(match(where("testItemRef").in(ids).andOperator(where("binaryContent").exists(true))), group("binaryContent.binaryDataId", "binaryContent.thumbnailId")); AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, Log.class, Map.class); return results.getMappedResults().stream().flatMap(it -> (Stream<String>) it.values().stream()).collect(toList()); }
@Override public SensorSubstate find(final String code) { final Locale locale = LocaleContextHolder.getLocale(); // Translations searchs are by language and by language_country final String localeField = "translations." + locale.getLanguage(); final String localeLongField = "translations." + locale.toString(); final Aggregation agg = newAggregation( project(Fields.from(Fields.field("code"), Fields.field("defaultDesc", "text"), Fields.field("translateLocShort", localeField), Fields.field("translateLocLong", localeLongField))), sort(Sort.Direction.DESC, "code"), match(where("code").is(code))); final AggregationResults<SensorSubstate> results = mongoOps.aggregate(agg, "sensorSubstate", SensorSubstate.class); return results.getMappedResults().isEmpty() ? new SensorSubstate() : results.getMappedResults().get(0); } }
@SuppressWarnings({ "rawtypes" }) @Override public List<String> findValuesWithMode(String projectName, String containsValue, String distinctBy, String mode) { Aggregation aggregation = newAggregation(match(where(PROJECT_ID_REFERENCE).is(projectName)), match(where(MODE).is(mode)), match(where(distinctBy).regex("(?i).*" + Pattern.quote(containsValue) + ".*")), group(distinctBy), limit(AUTOCOMPLETE_LIMITATION) ); AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, Launch.class, Map.class); return result.getMappedResults().stream().map(entry -> entry.get("_id").toString()).collect(toList()); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override public List<String> findDistinctValues(String projectName, String containsValue, String distinctBy) { //@formatter:off Aggregation aggregation = newAggregation( match(where(PROJECT_ID_REFERENCE).is(projectName)), unwind(distinctBy), match(where(distinctBy).regex("(?i).*" + Pattern.quote(containsValue) + ".*")), group(distinctBy), limit(AUTOCOMPLETE_LIMITATION)); //@formatter:on AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, Launch.class, Map.class); return result.getMappedResults().stream().map(it -> (String) it.get("_id")).collect(Collectors.toList()); }
@Override public List<SensorSubstate> findAll() { final Locale locale = LocaleContextHolder.getLocale(); // Translations searchs are by language and by language_country final String localeField = "translations." + locale.getLanguage(); final String localeLongField = "translations." + locale.toString(); final Aggregation agg = newAggregation(project(Fields.from(Fields.field("code"), Fields.field("defaultDesc", "text"), Fields.field("translateLocShort", localeField), Fields.field("translateLocLong", localeLongField))), sort(Sort.Direction.DESC, "code")); final AggregationResults<SensorSubstate> results = mongoOps.aggregate(agg, "sensorSubstate", SensorSubstate.class); return results.getMappedResults(); }