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

255
Views
Mongodb with spring, Group all rows in one and with disticnt values

I've realized a projection using mongoTemplate that gives me the result bellow:

{"resourcesInspected": ["CD0626UHEA", "CD0626UKE9"]}
{"resourcesInspected": ["CD0GNDPB1E"]}
{"resourcesInspected": ["CD0H7L789D", "CD0H7L8RF7"]}
{"resourcesInspected": ["CD0FTHYK2B"]}
{"resourcesInspected": ["CD04H5K4B1", "CD0725K788", "CD0725K58A"]}
{"resourcesInspected": ["CD06JXHJ8A", "CD04E9LCED"]}

to do so, I did this:

static final String resourcesInspected ="resourcesInspected";

ProjectionOperation projectionOperation = Aggregation
        .project(resourcesInspected).andExpression("split(resourcesInspected, ',')")
        .as(resourcesInspected)
        .andExclude("_id");

template.aggregate(newAggregation(projectionOperation),"kpi", DBObject.class).getMappedResults()
        .forEach(System.out::println);

Now what I really want is to group all the rows in one since it's the same field, and that in order to have in the end one per (key,value) with all the values are distinct, something like that:

{"resourcesInspected": ["CD0626UHEA", "CD0626UKE9","CD0626UHEZ","CXX0626UHEA"]}

for my context I need to use MongoOperations(mongoTemplate), I tried a lot of methods, but I don't get the result desired, could anyone help me in this ?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can go with

  • $unwind to deconstruct the array
  • $group to reconstruct without duplicate

Here is the script

db.collection.aggregate([
  {
    "$unwind": "$resourcesInspected"
  },
  {
    "$group": {
      "_id": null,
      "resourcesInspected": {
        "$addToSet": "$resourcesInspected"
      }
    }
  }
])

Working Mongo playground

So with your java code, you need to add following

 unwind("resourcesInspected"),
 group()
   .addToSet("$resourcesInspected").as("resourcesInspected")
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!