Java Code Examples for org.springframework.data.mongodb.core.aggregation.AggregationResults#getUniqueMappedResult()

The following examples show how to use org.springframework.data.mongodb.core.aggregation.AggregationResults#getUniqueMappedResult() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IssueRepositoryImpl.java    From mirrorgate with Apache License 2.0 7 votes vote down vote up
@Override
public double getBacklogEstimateByKeywords(final List<String> boards) {

    final Aggregation agg = newAggregation(
        match(Criteria
            .where("keywords").in(boards)
            .and("sprintAssetState").ne("ACTIVE")
            .and("type").in(Arrays.asList(IssueType.STORY.getName(), IssueType.BUG.getName()))
            .and("status").nin(Arrays.asList(IssueStatus.ACCEPTED.getName(), IssueStatus.DONE.getName()))
        ),
        group()
            .sum("estimation")
            .as("value"),
        project("value")
            .andExclude("_id")
    );

    final AggregationResults<DoubleValue> groupResults
        = mongoTemplate.aggregate(agg, "issue", DoubleValue.class);
    final DoubleValue val = groupResults.getUniqueMappedResult();

    return val == null ? 0 : val.value;
}
 
Example 2
Source File: IssueRepositoryImpl.java    From mirrorgate with Apache License 2.0 7 votes vote down vote up
@Override
public List<String> programIncrementBoardFeatures(
    final List<String> boards,
    final List<String> programIncrementFeatures
) {

    final Aggregation agg = newAggregation(
        match(Criteria
            .where("parentsKeys").in(programIncrementFeatures)
            .and("keywords").in(boards)
        ),
        unwind("parentsKeys"),
        group()
            .addToSet("parentsKeys")
            .as("features"),
        project("features")
            .andExclude("_id")
    );

    final AggregationResults<ProgramIncrementBoardFeatures> aggregationResult
        = mongoTemplate.aggregate(agg, "issue", ProgramIncrementBoardFeatures.class);

    return aggregationResult.getUniqueMappedResult() != null ? aggregationResult.getUniqueMappedResult().features
        : new ArrayList<>();
}
 
Example 3
Source File: IssueRepositoryImpl.java    From mirrorgate with Apache License 2.0 7 votes vote down vote up
@Override
public ProgramIncrementNamesAggregationResult getProductIncrementFromPiPattern(final Pattern pi) {

    final Aggregation agg = newAggregation(
        match(Criteria
            .where("type").is(IssueType.FEATURE.getName())
        ),
        project("piNames").andExclude("_id"),
        unwind("piNames"),
        match(Criteria
            .where("piNames").is(pi)
        ),
        group().addToSet("piNames").as("piNames")
    );

    final AggregationResults<ProgramIncrementNamesAggregationResult> aggregationResult
        = mongoTemplate.aggregate(agg, "issue", ProgramIncrementNamesAggregationResult.class);

    return aggregationResult.getUniqueMappedResult();
}
 
Example 4
Source File: CommitRepositoryImpl.java    From mirrorgate with Apache License 2.0 7 votes vote down vote up
@Override
public Double getSecondsToMaster(final List<String> repositories, final long timestamp) {
    final Aggregation agg = newAggregation(
        match(getCriteriaExpressionsForRepositories(repositories)
            .and("timestamp").gte(timestamp)
        ),
        group()
            .avg(
                Ceil.ceilValueOf(
                    Subtract.valueOf("$branches.refs/remotes/origin/master").subtract("timestamp")
                )
            ).as("value"),
        project("value")
            .andExclude("_id")
    );

    final AggregationResults<DoubleValue> secondsToMaster = mongoTemplate
        .aggregate(agg, "commits", DoubleValue.class);
    final DoubleValue seconds = secondsToMaster.getUniqueMappedResult();

    return seconds != null ? seconds.value : null;
}
 
Example 5
Source File: CommitRepositoryImpl.java    From mirrorgate with Apache License 2.0 6 votes vote down vote up
@Override
public Double getCommitsPerDay(final List<String> repositories, final long timestamp, final int daysBefore) {

    final Aggregation agg = newAggregation(
        match(getCriteriaExpressionsForRepositories(repositories)
            .and("timestamp").gte(timestamp)
        ),
        group()
            .count().as("value"),
        project("value")
            .andExclude("_id").and("value").divide(daysBefore)
    );

    final AggregationResults<DoubleValue> commitsPerDay
        = mongoTemplate.aggregate(agg, "commits", DoubleValue.class);
    final DoubleValue commits = commitsPerDay.getUniqueMappedResult();

    return commits != null ? commits.value : null;
}
 
Example 6
Source File: OrderRepositoryImpl.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 7
Source File: ZipsAggregationLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenStateWithLowestAvgCityPopIsND_theSuccess() {

    GroupOperation sumTotalCityPop = group("state", "city").sum("pop").as("cityPop");
    GroupOperation averageStatePop = group("_id.state").avg("cityPop").as("avgCityPop");
    SortOperation sortByAvgPopAsc = sort(new Sort(Direction.ASC, "avgCityPop"));
    ProjectionOperation projectToMatchModel = project().andExpression("_id").as("state")
      .andExpression("avgCityPop").as("statePop");
    LimitOperation limitToOnlyFirstDoc = limit(1);

    Aggregation aggregation = newAggregation(sumTotalCityPop, averageStatePop, sortByAvgPopAsc, limitToOnlyFirstDoc, projectToMatchModel);

    AggregationResults<StatePopulation> result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class);
    StatePopulation smallestState = result.getUniqueMappedResult();

    assertEquals("ND", smallestState.getState());
    assertTrue(smallestState.getStatePop()
      .equals(1645));
}
 
Example 8
Source File: ZipsAggregationLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenMaxTXAndMinDC_theSuccess() {

    GroupOperation sumZips = group("state").count().as("zipCount");
    SortOperation sortByCount = sort(Direction.ASC, "zipCount");
    GroupOperation groupFirstAndLast = group().first("_id").as("minZipState")
      .first("zipCount").as("minZipCount").last("_id").as("maxZipState")
      .last("zipCount").as("maxZipCount");

    Aggregation aggregation = newAggregation(sumZips, sortByCount, groupFirstAndLast);

    AggregationResults<Document> result = mongoTemplate.aggregate(aggregation, "zips", Document.class);
    Document document = result.getUniqueMappedResult();

    assertEquals("DC", document.get("minZipState"));
    assertEquals(24, document.get("minZipCount"));
    assertEquals("TX", document.get("maxZipState"));
    assertEquals(1671, document.get("maxZipCount"));
}
 
Example 9
Source File: OrderRepositoryImpl.java    From spring-graalvm-native with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 10
Source File: IssueRepositoryImpl.java    From mirrorgate with Apache License 2.0 5 votes vote down vote up
@Override
public SprintStats getSprintStatsByKeywords(final List<String> boards) {

    final Aggregation agg = newAggregation(
        match(Criteria
            .where("keywords").in(boards)
            .and("sprintAssetState").is("CLOSED")
            .and("type").in(Arrays.asList(IssueType.STORY.getName(), IssueType.BUG.getName()))
            .and("status").in(Arrays.asList(IssueStatus.ACCEPTED.getName(), IssueStatus.DONE.getName()))
        ),
        group("sprintName")
            .first("sprintBeginDate").as("start")
            .first("sprintEndDate").as("end")
            .sum("estimation").as("estimate"),
        group()
            .avg("estimate").as("estimateAvg")
            .avg(
                Ceil.ceilValueOf(
                    Divide.valueOf(
                        Subtract.valueOf("end").subtract("start")
                    ).divideBy(3600 * 1000 * 24)
                )
            ).as("daysDurationAvg"),
        project("daysDurationAvg", "estimateAvg")
            .andExclude("_id")
    );

    final AggregationResults<SprintStats> groupResults
        = mongoTemplate.aggregate(agg, "issue", SprintStats.class);

    return groupResults.getUniqueMappedResult();
}
 
Example 11
Source File: SprintRepositoryImpl.java    From mirrorgate with Apache License 2.0 5 votes vote down vote up
@Override
public Sprint getSprintForId(final String id, final String collectorId) {
    final Aggregation agg = newAggregation(
        match(where("sprintId").is(id).and("collectorId").is(collectorId)),
        firstSprintFields(group("sprintId"))
            .push(new BasicDBObject(ISSUE_FIELDS)).as("issues")
    );

    final AggregationResults<Sprint> aggregate =
        mongoTemplate.aggregate(agg, "issue", Sprint.class);

    return aggregate.getUniqueMappedResult();
}
 
Example 12
Source File: SpringBooksIntegrationTests.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Run a multi-faceted aggregation to get buckets by price (1-10, 10-50, 50-100 EURO) and by the first letter of the
 * author name.
 */
@Test
@SuppressWarnings("unchecked")
public void shouldCategorizeInMultipleFacetsByPriceAndAuthor() {

	Aggregation aggregation = newAggregation( //
			match(Criteria.where("volumeInfo.authors").exists(true).and("volumeInfo.publisher").exists(true)),
			facet() //
					.and(match(Criteria.where("saleInfo.listPrice").exists(true)), //
							replaceRoot("saleInfo"), //
							bucket("listPrice.amount") //
									.withBoundaries(1, 10, 50, 100))
					.as("prices") //

					.and(unwind("volumeInfo.authors"), //
							replaceRoot("volumeInfo"), //
							match(Criteria.where("authors").not().size(0)), //
							project() //
									.andExpression("substrCP(authors, 0, 1)").as("startsWith") //
									.and("authors").as("author"), //
							bucketAuto("startsWith", 10) //
									.andOutput("author").push().as("authors") //
					).as("authors"));

	AggregationResults<Document> result = operations.aggregate(aggregation, "books", Document.class);

	Document uniqueMappedResult = result.getUniqueMappedResult();

	assertThat((List<Object>) uniqueMappedResult.get("prices")).hasSize(3);
	assertThat((List<Object>) uniqueMappedResult.get("authors")).hasSize(8);
}