Example usage for org.springframework.data.mongodb.core.aggregation AggregationResults getMappedResults

List of usage examples for org.springframework.data.mongodb.core.aggregation AggregationResults getMappedResults

Introduction

In this page you can find the example usage for org.springframework.data.mongodb.core.aggregation AggregationResults getMappedResults.

Prototype

public List<T> getMappedResults() 

Source Link

Document

Returns the aggregation results.

Usage

From source file:com.epam.ta.reportportal.database.dao.TestItemRepositoryCustomImpl.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override//from w  w  w  . jav a 2 s .  c o m
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());
}

From source file:com.epam.ta.reportportal.database.dao.TestItemRepositoryCustomImpl.java

@Override
public List<String> findItemIdsByLaunchRef(List<String> launchRef) {
    Aggregation aggregation = newAggregation(match(where("launchRef").in(launchRef)), group("id"));
    AggregationResults<Map> aggregationResults = mongoTemplate.aggregate(aggregation, TestItem.class,
            Map.class);
    return aggregationResults.getMappedResults().stream().map(it -> it.get("_id").toString()).collect(toList());
}

From source file:com.epam.ta.reportportal.database.dao.TestItemRepositoryCustomImpl.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from w  ww .ja v a  2s  .  co m*/
public Map<String, String> getMostFailedTestCases(List<Launch> launches, String criteria) {
    Map<String, String> output = new HashMap<>();
    List<String> launchIds = launches.stream().map(Launch::getId).collect(toList());

    GroupOperation operationTotal = new GroupOperation(Fields.fields("$name")).count().as("count");
    Aggregation aggregationTotal = newAggregation(match(where(LAUNCH_REFERENCE).in(launchIds)),
            match(where(HAS_CHILD).is(false)), operationTotal);
    AggregationResults<Map> resultTotal = mongoTemplate.aggregate(aggregationTotal, TestItem.class, Map.class);
    Map<String, String> values = resultTotal.getMappedResults().stream()
            .collect(toMap(key -> key.get("_id").toString(), value -> value.get("count").toString()));

    GroupOperation operation = new GroupOperation(Fields.fields("$name")).count().as("count").last("$startTime")
            .as("last");
    Aggregation aggregation = newAggregation(match(where(LAUNCH_REFERENCE).in(launchIds)),
            match(where(criteria).is(1)), match(where(HAS_CHILD).is(false)), operation);

    AggregationResults<Map> result = mongoTemplate.aggregate(aggregation, TestItem.class, Map.class);
    for (Map<String, ?> entry : result.getMappedResults()) {
        String itemName = String.valueOf(entry.get("_id"));
        String count = String.valueOf(entry.get("count"));
        Date date = (Date) entry.get("last");
        String total = values.get(itemName);
        // FIXME Update dirty # separator with common case
        // And update after {@link MostFailedTestCasesFilterStrategy}
        output.put(itemName, count + "#" + date.getTime() + "#" + total);
    }
    return output;
}

From source file:org.ingini.mongodb.spring.example.aggregation.TestAggregationFramework.java

/**
 * Example taken from https://github.com/mongodb/mongo-ruby-driver/wiki/Aggregation-Framework-Examples
 * Command line import: mongoimport --drop --db aggregation_test_db --collection name_days name_days.json
 * <p>//w w  w. ja v  a 2s.c o  m
 *      db.name_days.aggregate({$project : {names : 1, _id : 0}},
 *                             {$unwind : '$names'},
 *                             {$group : {_id: '$names', counter: {$sum: 1}}},
 *                             {$sort : {counter: -1}},
 *                             {$limit : 10});
 * </p>
 */
@Test
public void shouldFindThe10MostCommonNames() {
    //GIVEN
    CollectionManager.cleanAndFill(mongoTemplate.getDb(), "name_days.json", NameData.COLLECTION_NAME);
    int limit = 10;

    //WHEN
    AggregationResults<AggregatedNameData> aggregationResult = mongoTemplate.aggregate(
            Aggregation.newAggregation(NameData.class, Aggregation.project("names").andExclude("_id"),
                    Aggregation.unwind("names"), Aggregation.group("names").count().as("counter"),
                    Aggregation.sort(Sort.Direction.DESC, "counter"), Aggregation.limit(limit)),
            AggregatedNameData.class);

    //THEN
    assertThat(aggregationResult.getMappedResults()).hasSize(10);
    assertThat(aggregationResult.getMappedResults().get(0)).isEqualTo(new AggregatedNameData("Jana", 21));

}

From source file:org.devgateway.ocds.web.rest.controller.FundingByLocationController.java

@ApiOperation(value = "Total estimated funding (tender.value) grouped by "
        + "tender.items.deliveryLocation and also grouped by year."
        + " The endpoint also returns the count of tenders for each location. "
        + "It responds to all filters. The year is calculated based on tender.tenderPeriod.startDate")
@RequestMapping(value = "/api/fundingByTenderDeliveryLocation", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> fundingByTenderDeliveryLocation(
        @ModelAttribute @Valid final YearFilterPagingRequest filter) {

    DBObject project = new BasicDBObject();
    project.put("tender.items.deliveryLocation", 1);
    project.put("tender.value.amount", 1);
    project.put(Keys.YEAR, new BasicDBObject("$year", "$tender.tenderPeriod.startDate"));

    Aggregation agg = newAggregation(/*from  ww  w .j  a v a 2 s. c om*/
            match(where("tender").exists(true).and("tender.tenderPeriod.startDate").exists(true)
                    .andOperator(getYearDefaultFilterCriteria(filter, "tender.tenderPeriod.startDate"))),
            new CustomProjectionOperation(project), unwind("$tender.items"),
            unwind("$tender.items.deliveryLocation"),
            match(where("tender.items.deliveryLocation.geometry.coordinates.0").exists(true)),
            group(Keys.YEAR, "tender." + Keys.ITEMS_DELIVERY_LOCATION).sum("$tender.value.amount")
                    .as(Keys.TOTAL_TENDERS_AMOUNT).count().as(Keys.TENDERS_COUNT),
            sort(Direction.ASC, Keys.YEAR)
    //,skip(filter.getSkip()), limit(filter.getPageSize())
    );

    AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class);
    List<DBObject> tagCount = results.getMappedResults();
    return tagCount;
}

From source file:org.devgateway.ocds.web.rest.controller.FundingByLocationController.java

@ApiOperation("Calculates percentage of releases with tender with at least one specified delivery location,"
        + " that is the array tender.items.deliveryLocation has to have items."
        + "Filters out stub tenders, therefore tender.tenderPeriod.startDate has to exist.")
@RequestMapping(value = "/api/qualityFundingByTenderDeliveryLocation", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> qualityFundingByTenderDeliveryLocation(
        @ModelAttribute @Valid final YearFilterPagingRequest filter) {

    DBObject project = new BasicDBObject();
    project.putAll(filterProjectMap);/*from  w w  w  . ja  v a  2  s  .  c o  m*/
    project.put(Fields.UNDERSCORE_ID, "$tender._id");
    project.put("tenderItemsDeliveryLocation", new BasicDBObject("$cond",
            Arrays.asList(new BasicDBObject("$gt", Arrays.asList("$tender.items.deliveryLocation", 0)), 1, 0)));

    DBObject project1 = new BasicDBObject();
    project1.put(Fields.UNDERSCORE_ID, 0);
    project1.put(Keys.TOTAL_TENDERS_WITH_START_DATE, 1);
    project1.put(Keys.TOTAL_TENDERS_WITH_START_DATE_AND_LOCATION, 1);
    project1.put(Keys.PERCENT_TENDERS_WITH_START_DATE_AND_LOCATION, new BasicDBObject("$multiply",
            Arrays.asList(new BasicDBObject("$divide",
                    Arrays.asList("$totalTendersWithStartDateAndLocation", "$totalTendersWithStartDate")),
                    100)));

    Aggregation agg = newAggregation(
            match(where("tender.tenderPeriod.startDate").exists(true)
                    .andOperator(getYearDefaultFilterCriteria(filter, "tender.tenderPeriod.startDate"))),
            unwind("$tender.items"), new CustomProjectionOperation(project),
            group(Fields.UNDERSCORE_ID_REF).max("tenderItemsDeliveryLocation")
                    .as("hasTenderItemsDeliverLocation"),
            group().count().as("totalTendersWithStartDate").sum("hasTenderItemsDeliverLocation").as(
                    Keys.TOTAL_TENDERS_WITH_START_DATE_AND_LOCATION),
            new CustomProjectionOperation(project1)
    //,skip(filter.getSkip()),limit(filter.getPageSize())
    );

    AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class);
    List<DBObject> tagCount = results.getMappedResults();
    return tagCount;
}

From source file:org.devgateway.ocds.web.rest.controller.FundingByLocationController.java

@ApiOperation(value = "Planned funding by location by year. Returns the total amount of planning.budget"
        + " available per planning.budget.projectLocation, grouped by year. "
        + "This will return full location information, including geocoding data."
        + "Responds only to the procuring entity id filter: tender.procuringEntity._id")
@RequestMapping(value = "/api/plannedFundingByLocation", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> plannedFundingByLocation(@ModelAttribute @Valid final YearFilterPagingRequest filter) {

    DBObject vars = new BasicDBObject();
    vars.put("numberOfLocations", new BasicDBObject("$size", "$planning.budget.projectLocation"));
    vars.put("planningBudget", "$planning.budget.amount.amount");
    DBObject in = new BasicDBObject("$divide", Arrays.asList("$$planningBudget", "$$numberOfLocations"));

    DBObject let = new BasicDBObject();
    let.put("vars", vars);
    let.put("in", in);

    DBObject dividedTotal = new BasicDBObject("$let", let);

    DBObject project = new BasicDBObject();
    project.put("planning.budget.projectLocation", 1);
    project.put("cntprj", new BasicDBObject("$literal", 1));
    project.put("planning.budget.amount.amount", 1);
    project.put("dividedTotal", dividedTotal);
    project.put(Keys.YEAR, new BasicDBObject("$year", "$planning.bidPlanProjectDateApprove"));

    Aggregation agg = newAggregation(/*  ww  w . j a v a2  s .c o  m*/
            match(where("planning").exists(true).and("planning.budget.projectLocation.0").exists(true)
                    .andOperator(getProcuringEntityIdCriteria(filter),
                            getYearFilterCriteria(filter, "planning.bidPlanProjectDateApprove"))),
            new CustomProjectionOperation(project), unwind("$planning.budget.projectLocation"),
            match(where("planning.budget.projectLocation.geometry.coordinates.0").exists(true)),
            group("year", "planning.budget.projectLocation").sum("$dividedTotal").as(Keys.TOTAL_PLANNED_AMOUNT)
                    .sum("$cntprj").as("recordsCount"),
            sort(Direction.ASC, Keys.YEAR)
    //, skip(filter.getSkip()), limit(filter.getPageSize())
    );

    AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class);
    List<DBObject> tagCount = results.getMappedResults();
    return tagCount;

}

From source file:org.devgateway.ocds.web.rest.controller.FundingByLocationController.java

@ApiOperation("Calculates percentage of releases with planning with at least one specified location,"
        + " that is the array planning.budget.projectLocation has to be initialzied."
        + "Filters out stub planning, therefore planning.budget.amount has to exist."
        + "Responds only to the procuring entity id filter: tender.procuringEntity._id")
@RequestMapping(value = "/api/qualityPlannedFundingByLocation", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> qualityPlannedFundingByLocation(
        @ModelAttribute @Valid final DefaultFilterPagingRequest filter) {

    DBObject project = new BasicDBObject();
    project.putAll(filterProjectMap);//from   w  ww . j ava2  s  .  co m
    project.put("planning.budget.projectLocation", 1);
    project.put("planning.budget.amount", 1);
    project.put(Fields.UNDERSCORE_ID, 0);

    DBObject group = new BasicDBObject();
    group.put(Fields.UNDERSCORE_ID, null);
    group.put(Keys.TOTAL_PLANS_WITH_AMOUNTS, new BasicDBObject("$sum", 1));
    group.put(Keys.TOTAL_PLANS_WITH_AMOUNTS_AND_LOCATION,
            new BasicDBObject("$sum",
                    new BasicDBObject("$cond",
                            Arrays.asList(new BasicDBObject("$gt", Arrays.asList(
                                    new BasicDBObject("$size",
                                            new BasicDBObject("$ifNull", Arrays.asList(
                                                    "$planning.budget.projectLocation", ArrayUtils.toArray()))),
                                    0)), 1, 0))));

    DBObject project2 = new BasicDBObject();
    project2.put(Fields.UNDERSCORE_ID, 0);
    project2.put(Keys.TOTAL_PLANS_WITH_AMOUNTS, 1);
    project2.put(Keys.TOTAL_PLANS_WITH_AMOUNTS_AND_LOCATION, 1);
    project2.put(Keys.PERCENT_PLANS_WITH_AMOUNTS_AND_LOCATION,
            new BasicDBObject("$multiply",
                    Arrays.asList(new BasicDBObject("$divide",
                            Arrays.asList("$totalPlansWithAmountsAndLocation", "$totalPlansWithAmounts")),
                            100)));

    Aggregation agg = newAggregation(new CustomProjectionOperation(project),
            match(where("planning.budget.amount").exists(true)
                    .andOperator(getProcuringEntityIdCriteria(filter))),
            new CustomGroupingOperation(group), new CustomProjectionOperation(project2)
    //, skip(filter.getSkip()),limit(filter.getPageSize())
    );

    AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, "release", DBObject.class);
    List<DBObject> tagCount = results.getMappedResults();
    return tagCount;
}