Home > Back-end >  Mongodb with spring, Group all rows in one and with disticnt values
Mongodb with spring, Group all rows in one and with disticnt values

Time:02-19

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 ?

CodePudding user response:

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")
  • Related