【问题标题】:Query for mongoRepository list查询 mongoRepository 列表
【发布时间】:2019-09-16 03:05:42
【问题描述】:

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

  • 日期(日期对象)
  • offerType (str)

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


示例

文件:

  1. 日期:10-04-2019,offerType:offer1
  2. 日期:11-04-2019,offerType:offer3
  3. 日期:15-04-2019,offerType:offer2
  4. 日期: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


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

      我们还有另一个使用查询的选项

      @Query(value = "{ 'groupId' :  ?0 , 'user.$id' : {$in: ?1} }", delete = true)
          List<GroupUser> deleteUserInGroup(String groupId, List<ObjectId> userId);
      

      你可以试试。

      【讨论】:

        猜你喜欢
        • 2017-10-24
        • 1970-01-01
        • 2017-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 2017-05-05
        • 2016-03-29
        相关资源
        最近更新 更多