java - 查询 mongoRepository 列表

标签 java mongodb spring-boot mongorepository

我有一个 MongoDB 集合,其中包含具有以下字段的文档:

  • 日期(日期对象)
  • 报价类型(str)

我想使用 MongoRepository 编写一个方法来查找日期范围内的所有文档,并且 OfferType 包含列表中提供的字符串之一

<小时/>

示例

文件:

  1. 日期:2019 年 10 月 4 日,offerType:offer1
  2. 日期:2019 年 4 月 11 日,offerType:offer3
  3. 日期:2019 年 4 月 15 日,offerType:offer2
  4. 日期:2019 年 4 月 15 日,offerType:offer1

我想要:

  • 日期在 2019 年 4 月 9 日至 2019 年 4 月 12 日之间
  • 以下优惠:优惠 1、优惠 3

在前面的示例中,我将获取文档 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 以搜索可以包含作为参数传递的列表值之一的字段
这个实现有什么问题吗?有更好的方法来实现这个查询吗?

最佳答案

这比我想象的要简单。我为感兴趣的人发布答案:

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);


}

所以重点是使用关键字In

关于java - 查询 mongoRepository 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55870340/

相关文章:

java - 在 Android 中显示 httpGet 和响应之间的进度图像

mongodb - mongo 未连接但已安装并显示版本

传感器数据的 mongodb 结构

javascript - 过滤子文档数组,同时如果为空仍返回父数据

java - 如何在 Spring Boot 中从属性文件读取正则表达式模式

java - Controller 中构造函数的参数 0 需要一个类型为 Service 类的 bean,但无法找到

解析大型 xml 文件时发生 Java 堆空间错误

java - 比较 HashMap 中的键和值

spring-boot - Spring 启动: excluding some autoconfigured beans

java - Bitmap.compress 导致文件太大