Sumanth Varada
Sumanth Varada

Reputation: 1190

How to use between and where condition together in Spring Data Mongo DB?

I have a document called Employee. I want to query all the employees whose designation is "Developer" and joiningDate between 2019 and 2020.

class Employee{
    private String name;
    private String designation;
    private Date joiningDate;
}

**// i want where condition on designation to be included in the following** 
@Repository
public interface EmployeeRepository extends MongoRepository<Employee, String> {
    @Query("{'joiningDate' : {$gte : ?0, $lte : ?1}}")
    public List<Employee> findByJoiningDateBetween(LocalDateTime startTime, LocalDateTime endTime);
}

Upvotes: 0

Views: 926

Answers (2)

dasunse
dasunse

Reputation: 3089

In your repository use this way

List<Employee> findByJoiningDateBetween(Date startDate, Date endDate);

refer

Upvotes: 1

Dmitry Ionash
Dmitry Ionash

Reputation: 821

Really, this is not JPA, this is Spring Data MongoDB.

This is not a Document, the Document must be annotated as @Document and have @Id (String or better ObjectId).

If you want to use a complex query, maybe the better way to use own repository method implementation:

public interface EmployeeRepository extends MongoRepository<Employee, String>, EmployeeRepositoryBase {
}

public interface EmployeeRepositoryBase {
    List<Employee> findByJoiningDateBetween(Date startDate, Date endDate);
}

@Repository
public class EmployeeRepositoryImpl implements EmployeeRepositoryBase {

    @Autowired
    private MongoTemplate mongoTemplate;

    public List<Employee> findJoiningDateBetween(final Date startDate, final Date endDate) {
        final var query = Query.query(Criteria.where("...").is(...).and("...").gte(...).lte(...);
        return mongoTemplate(query, Employee.class);
    }
}

Upvotes: 1

Related Questions