I have a MongoDB collection with documents with the following fields:
I want to write a method with MongoRepository to find all the documents that has date in a range of dates and offerType contains one of the string provided in a list.
Documents:
I want:
In the previous example I would obtain documents 1 and 2.
I use MongoRepository and a custom Object which contains the fields I require:
import java.util.Date;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ReportVocalOrderRepository extends MongoRepository<ReportVocalOrder, String> {
List<ReportVocalOrder> findByDateBetween(Date startDate, Date endDate, Pageable pageable);
List<ReportVocalOrder> findByDateBetweenAndOfferTypeContaining(Date startDate, Date endDate, List<String> offers, Pageable pageable);
}
Here is the document class:
@JsonInclude(Include.NON_NULL)
@Document(collection = Constants.Mongo.Collections.VOCAL_ORDER_REPORT)
@ApiModel
public class ReportVocalOrder {
@Id
private String id;
private Date date;
private String offerType;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getOfferType() {
return offerType;
}
public void setOfferType(String offerType) {
this.offerType = offerType;
}
}
The first method of the MongoRepository works fine; the second one instead returns an empty list.
The problem is to query the mongoRepository to search a field that can contain one of the values of the list passed as an argument.
What's wrong with this implementation? There's a better way to implement this query?
It was simpler than I thought. I post an answer for whom is interested:
import java.util.Date;
import java.util.List;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface ReportVocalOrderRepository extends MongoRepository<ReportVocalOrder, String> {
List<ReportVocalOrder> findByDateBetweenAndOfferTypeIn(Date startDate, Date endDate, List<String> offers, Pageable pageable);
}
So the point is to use the keyword In
.