MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

Mongodb $lookup in Spring Data Mongo

Zusammenführen zweier Sammlungen mit Spring Data MongoDB

Mitarbeiterklasse

class Employee {
    private String _id;
    private String name;
    private String dept_id;
}

Abteilungsklasse

class Department {
    private String _id;
    private String dept_name;
}

Mitarbeiterergebnisklasse

public class EmpDeptResult {

    private String _id;
    private String name;
    private List<Object> departments;
}

EmployeeService-Klasse

public class EmployeeService {

    @Autowired
    private MongoTemplate mongoTemplate;

    private Logger LOGGER = LoggerFactory.getLogger(EmployeeService.class);

    public void lookupOperation(){
    LookupOperation lookupOperation = LookupOperation.newLookup()
                        .from("Department")
                        .localField("dept_id")
                        .foreignField("_id")
                        .as("departments");

    Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("_id").is("1")) , lookupOperation);
        List<EmpDeptResult> results = mongoTemplate.aggregate(aggregation, "Employee", EmpDeptResult.class).getMappedResults();
        LOGGER.info("Obj Size " +results.size());
    }
}