Search code examples
javamongodbspring-bootmongorepository

Query for mongoRepository list


I have a MongoDB collection with documents with the following fields:

  • date (Date obj)
  • offerType (str)

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.


Example

Documents:

  1. date: 10-04-2019, offerType: offer1
  2. date: 11-04-2019, offerType: offer3
  3. date: 15-04-2019, offerType: offer2
  4. date: 15-04-2019, offerType: offer1

I want:

  • dates between 9-04-2019 and 12-04-2019
  • following offers: offer1, offer3

In the previous example I would obtain documents 1 and 2.


My code

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?


Solution

  • 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.