Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

264
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda