Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
Is it possible to round a number with Spring data MongoDB aggregations?

I have the following aggregation pipeline to calculate the top rated brands from a collection of phones with their reviews embedded.

public Document findTopRatedBrands(int minReviews, int results) {
        UnwindOperation unwindOperation = unwind("reviews");
        GroupOperation groupOperation = group("$brand").avg("$reviews.rating")
                        .as("avgRating").count().as("numReviews");
        MatchOperation matchOperation = match(new Criteria("numReviews").gte(minReviews));
        SortOperation sortOperation = sort(Sort.by(Sort.Direction.DESC, "avgRating",
                "numReviews"));
        LimitOperation limitOperation = limit(results);
        ProjectionOperation projectionOperation = project().andExpression("_id").as
                ("brand").andExpression("avgRating").as("rating").andExclude("_id")
                .andExpression("numReviews").as("reviews");
        Aggregation aggregation = newAggregation(unwindOperation, groupOperation, matchOperation,
                sortOperation, limitOperation, projectionOperation);
        AggregationResults<Phone> result = mongoOperations
                .aggregate(aggregation, "phones", Phone.class);
        return result.getRawResults();
    }

An example of document in the phones collection is this:

{
    "_id": {
        "$oid": "61e1cc8f452d0aef89d9125f"
    },
    "brand": "Samsung",
    "name": "Samsung Galaxy S7",
    "releaseYear": 2016,
    "reviews": [{
        "_id": {
            "$oid": "61d4403b86913bee0245c171"
        },
        "rating": 2,
        "dateOfReview": {
            "$date": "2019-12-24T00:00:00.000Z"
        },
        "title": "Won't do that again.",
        "body": "I could not use with my carrier. Sent it back.",
        "username": "bigrabbit324"
    }]
} 

I would like to sort by avgRating (rounded to the first decimal place), and secondly by the number of reviews. Now the average rating it's not rounded so it gives always different values, so I can't sort by number of reviews also. I have seen the ArithmeticOperators.Round class but I don't understand how to include it here if possible.

An example of result is the following:

[Document{{brand=Nokia, rating=3.25, reviews=4}}] 

I would like to have 3.2 as rating.

This works in Mongo Compass:

    $project: {
        _id: 0,
        brand: '$_id',
        rating: { $round: ['$avgRating', 1] }
    }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

try

ProjectionOperation roundAverageRating = Aggregation.project("avgRating", "numReviews")
    .and(ArithmeticOperators.Round.roundValueOf("avgRating").place(1))
    .as("avgRatingRounded");
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!