Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

256
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda