Search code examples
javaspringspring-dataspring-data-mongodb

Spring Data Mongo: How to return nested object by its field?


I have domain:

class Company {
    List<Job> jobs;
}

Is there a way to return nested object from collection like:

@Repository
public interface CompanyRepository extends MongoRepository<Company, String>{
    Job findByJobId(String jobId);
}

Solution

  • I have to make some assumptions about the structure of your Job model, but assuming something like this:

    public class Job {
        private String id;
        // other attributes and methods
    }
    

    ... and assuming that this model is embedded in your Company model, and not represented in another collection, you will have to go the custom implementation via MongoTemplate route. The Spring Data query API is not going to be able to figure out how to get what you want, so you must implement the method yourself.

    @Repository
    public interface CompanyRepository extends CompanyOperations, MongoRepository<Company, String>{
    } 
    
    public interface CompanyOperations {
        Job findByJobId(String jobId);
    }
    
    public class CompanyRepositoryImpl implements CompanyOperations {
        @Autowired private MongoTemplate mongoTemplate;
    
        @Override
        public Job findByJobId(String jobId){
            Company company = mongoTemplate.findOne(new Query(Criteria.where("jobs.id").is(jobId)), Company.class);
            return company.getJobById(jobId); //implement this method in `Company` and save yourself some trouble.
        }
    }