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

173
Views
java MongoTemplate agregado con documento anidado del proyecto

tengo un documento

 { "errors" : [ { "priority" : 3, "category" : "aaa" "other":"nothing" }, { "priority" : 4, "category" : "bbb" "other":"nothing" }, { "priority" : 2, "category" : "ccc" "other":"nothing" }, { "priority" : 3, "category" : "ddd" "other":"nothing" }, { "priority" : 2, "category" : "eee" "other":"nothing" } ], "file_name" : "xxx.json", "vehicle_id" : "esdf", "day" : "2022-03-08" }

Ejecuto un comando con el cliente js.

 db.wty_test.aggregate({ $project: { '_id': 0, 'errors.priority': 1, 'errors.category': 1, 'file_name': 1, 'vehicle_id': 1, } })

Obtengo el resultado que quiero. ingrese la descripción de la imagen aquí Los errores es una matriz que contiene objetos.

Ahora necesito sobrescribir este comando con el cliente java (springboot-data-mongo). Este es mi código Java.

 import org.springframework.data.mongodb.core.MongoTemplate; ... Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("errors.priority", "errors.category", "file_name", "vehicle_id")); mongoTemplate.aggregate(aggregation, "wty_test", HashMap.class).getMappedResults();

ingrese la descripción de la imagen aquí La prioridad y categoría no está en errores.

¿Cómo usar java para obtener el mismo resultado que js?

Intento el anidado. Pero no es lo que quiero.

ingrese la descripción de la imagen aquí


ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Aquí hay una manera de obtener el resultado deseado.

 Document projectn = new Document("$project", new Document("_id", 0L) .append("file_name", 1L) .append("vehicle_id", 1L) .append("errors", new Document("$map", new Document("input", "$errors") .append("in", new Document("priority", "$$this.priority") .append("category", "$$this.category") ) ) ) ); List<Document> pipeline = Arrays.asList(projectn); List<Document> results = mongoOps.getCollection("collection_name") .aggregate(pipeline) .into(new ArrayList<>());

Tenga en cuenta que esto utiliza la sintaxis de consulta de la API del controlador Java de MongoDB y el Document es org.bson.Document . La conversión de la consulta nativa a Java Driver utiliza el operador de matriz de agregación $map (y parece que esa es la (quizás única) manera).

Con MongoTemplate.aggregate el código es:

 Aggregation agg = newAggregation( project() .and( VariableOperators.Map.itemsOf("errors") .as("e") .andApply(ctx -> new Document("priority", "$$e.priority").append("category", "$$e.category") )) .as("errors") .andExclude("_id") .andInclude("file_name", "vehicle_id") ); AggregationResults<Document> results = mongoOps.aggregate(agg, "collection_name", Document.class);


Metodo alternativo:

En caso de que su consulta sea solo sobre la proyección , puede usar la siguiente consulta usando el método MongoTemplate#find . Esto es mucho más simple de construir y entender:

 db.collection.find( {}, // your query filter { _id: 0, 'errors.category': 1, 'errors.priority': 1, file_name: 1, vehicle_id: 1 } )

La versión de MongoTemplate :

 Query query = new Query(); query.fields() .include("errors.priority", "errors.category", "file_name", "vehicle_id") .exclude("_id"); List<Document> results = mongoOps.find(query, Document.class, "collection_name");
about 4 years ago · Juan Pablo Isaza Report

0

Desea utilizar la función nested() , así:

 AggregationOperation project = Aggregation.project("file_name", "vehicle_id"). and("errors").nested(Fields.fields("priority","category")) Aggregation aggregation = Aggregation.newAggregation(project);
about 4 years ago · Juan Pablo Isaza 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!