Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm new to MongoDB!

Can anyone please help me on how to write java code to convert the below mongo aggregation query ? Currently, I'm writing this in a spring boot application having "spring-boot-starter-data-mongodb" as a dependency. I'm thinking to use Mongo Template to fetch grouped docs using the below Query.

db.getCollection('test').aggregate([  
    $group: {
        _id: { name: "$name", zip: "$recipients.0.address.postalcode" },
        groupedDocs: { $addToSet: "$$ROOT" }
                Here is post with grouping aggregation using MongoTemplate: stackoverflow.com/questions/59639379/…
– prasad_
                May 5, 2021 at 7:41

Using the MongoTemplate is the right idea. You need to create your aggregation first like this:

var aggregation = Aggregation.newAggregation(
    Aggregation.group(Fields.from(
            Fields.field("name"),
            Fields.field("zip", "recipients.0.address.postalcode")
    ).addToSet("$$ROOT")

Of course you could use static imports to make it more concise, I wrote it like this so you can find the classes better. I am not sure about the $$ROOT reference, you might have to look that up. With this, you can call the MongoTemplate:

return mongoTemplate.aggregate(aggregation, "Test", Test.class);
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.