Mongodb $lookup in Spring data mongo

Anh Bui picture Anh Bui · Mar 22, 2016 · Viewed 23.8k times · Source

I'm a new Mongodb and I have a problem with $lookup with java spring.

I would like to use this shell in Spring data

db.NewFeed.aggregate([
    {
        $match : {username : "user001"}
    },
    {
      $lookup:
        {
          from: "NewfeedContent",
          localField: "content.contentId",
          foreignField: "_id",
          as: "NewfeedContent"
        }
   }
])

I found on Google but no answer yet.

Answer

Dhiren Chauhan picture Dhiren Chauhan · Mar 29, 2018

Joining Two Collections with Spring Data MongoDB

Employee Class

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

Department Class

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

Employee Result Class

public class EmpDeptResult {

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

EmployeeService Class

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());
    }
}