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

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

Introduction

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

Prototype

@Nullable
public T getUniqueMappedResult() 

Source Link

Document

Returns the unique mapped result.

Usage

From source file:it.f2informatica.mongodb.repositories.impl.ConsultantRepositoryImpl.java

@Override
public Education findEducation(String consultantId, String educationId) {
    Aggregation aggregation = newAggregation(match(where("id").is(consultantId)), group("educationList"),
            unwind(previousOperation()),
            match(where(previousOperation() + "." + Fields.UNDERSCORE_ID).is(educationId)));
    AggregationResults<Education> aggregationResults = mongoTemplate.aggregate(aggregation, Consultant.class,
            Education.class);
    return aggregationResults.getUniqueMappedResult();
}

From source file:it.f2informatica.mongodb.repositories.impl.ConsultantRepositoryImpl.java

@Override
public Experience findExperience(String consultantId, String experienceId) {
    Aggregation aggregation = newAggregation(match(where("id").is(consultantId)), group("experiences"),
            unwind(previousOperation()),
            match(where(previousOperation() + "." + Fields.UNDERSCORE_ID).is(experienceId)));
    AggregationResults<Experience> aggregationResults = mongoTemplate.aggregate(aggregation, Consultant.class,
            Experience.class);
    return aggregationResults.getUniqueMappedResult();
}

From source file:example.springdata.mongodb.aggregation.SpringBooksIntegrationTests.java

/**
 * 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.//from   w  w  w.j  a  v  a 2s  .co  m
 */
@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);
}

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

@Override
public long getPageNumber(String entityId, Filter filterable, Pageable pageable) {
    Class<T> javaType = this.getEntityInformation().getJavaType();
    ImmutableList.Builder<AggregationOperation> pipelineBuilder = ImmutableList.<AggregationOperation>builder()
            .add(new MatchOperation(
                    new Criteria().andOperator(toArray(toCriteriaList(filterable), Criteria.class))) {
                @Override/* w w  w . j  a v a2  s.com*/
                public DBObject toDBObject(AggregationOperationContext context) {
                    return super.toDBObject(new TypeBasedAggregationOperationContext(javaType,
                            mongoOperations.getConverter().getMappingContext(), queryMapper));
                }
            });

    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());
}

From source file:example.springdata.mongodb.aggregation.OrderRepositoryImpl.java

/**
 * 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.
 * //from  w ww  .  j a  va 2s.  com
 * @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();
}