/** * 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(); } }
@Autowired private MongoOperations mongoOperations; ... public List<Person> findByAddressZipCode(int zip) { List<AggregationOperation> list = new ArrayList<AggregationOperation>(); list.add(Aggregation.unwind("address")); list.add(Aggregation.match(Criteria.where("address.zip").is(zip))); list.add(Aggregation.group("firstName", "lastName").push("address").as("address")); list.add(Aggregation.project("firstName", "lastName", "address")); TypedAggregation<Person> agg = Aggregation.newAggregation(Person.class, list); return mongoOperations.aggregate(agg, Person.class, Person.class).getMappedResults(); }
public Boolean getOrderGiftCardCount(Integer quantity) { MongoOperations mongoOperations = getMongoConnection(); MatchOperation match = new MatchOperation(Criteria.where("quantity").gt(quantity)); GroupOperation group = Aggregation.group("giftCard").sum("giftCard").as("count"); Aggregation aggregate = Aggregation.newAggregation(match, group); AggregationResults<Order> orderAggregate = mongoOperations.aggregate(aggregate, "order", Order.class); if (orderAggregate != null) { System.out.println("Output ====>" + orderAggregate.getRawResults().get("result")); System.out.println("Output ====>" + orderAggregate.getRawResults().toMap()); } return true; }
@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(); }
@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); } }
@Override public List<SensorSubstate> findAll(final SensorState state) { 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("state").is(state))); final AggregationResults<SensorSubstate> results = mongoOps.aggregate(agg, "sensorSubstate", SensorSubstate.class); return results.getMappedResults(); }
@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()); }
); return mongoOperations.aggregate(a, mongoOperations.getCollectionName(Project.class), UserRoleDetails.class).getUniqueMappedResult();