【发布时间】:2019-09-16 03:05:42
【问题描述】:
我有一个 MongoDB 集合,其中包含具有以下字段的文档:
- 日期(日期对象)
- offerType (str)
我想用 MongoRepository 编写一个方法查找日期范围内的所有文档,并且 offerType 包含列表中提供的字符串之一。
示例
文件:
- 日期:10-04-2019,offerType:offer1
- 日期:11-04-2019,offerType:offer3
- 日期:15-04-2019,offerType:offer2
- 日期:15-04-2019,offerType:offer1
我想要:
- 日期在 2019 年 9 月 4 日到 2019 年 4 月 12 日之间
- 以下优惠:offer1、offer3
在前面的示例中,我将获取文档 1 和 2。
我的代码
我使用 MongoRepository 和一个自定义对象,其中包含我需要的字段:
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);
}
这里是文档类:
@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;
}
}
MongoRepository 的第一个方法工作正常;第二个返回一个空列表。
问题是查询 mongoRepository 以搜索可以包含作为参数传递的列表值之一的字段。
这个实现有什么问题?有更好的方法来实现这个查询吗?
【问题讨论】:
标签: java mongodb spring-boot mongorepository