spring 数据 MongoDB ,比较同一文档中的两个字段

spring Data MongoDB , compare two fields in the same document

我有以下合集:

@Data
@Document(collection = "compte_titre_composition")
public class CompteTitreComposition {

  @Id private String id;

  @Field("numero_compte_titre")
  private String numeroCompte;

  private BigDecimal valorisationActuelle;

  @Field("date_valorisation")
  private Date dateValorisation;

  @Field("date_validite")
  private Date dateValidite;

}

我想 select 作为 dateValorisation 的元素, numeroCompte 等于方法参数和 dateValorisation >= dateValidite ,所以我写了下面的代码:

  public List<EvolutionCompteTitreDto> getCpteTitreEvolution(
      String numeroCompte, LocalDateTime dateDebut, LocalDateTime dateFin) {

    List<AggregationOperation> listAggregations = new ArrayList<>();

    AggregationOperation matchByCpteAndDateValorisation =
        Aggregation.match(
            Criteria.where("numeroCompte")
                .is(numeroCompte)
                .and("dateValorisation")
                .gte("dateValidite")
                .gte(dateDebut)
                .lte(dateFin));

除了这个条件 dateValorisation >= dateValidite(似乎没有考虑)所有条件都正常工作代码没有考虑它

问题来自错误的比较 gte() 方法将对象作为参数进行比较 it.In 在比较同一文档中的两个字段的情况下,我们应该创建这样的表达式:

AggregationOperation projetByValidDate =
    Aggregation.project(
            "dateValorisation",
            "dateValidite",
            "numeroCompte")
        .andExpression("dateValorisation - dateValidite")
        .as("duration");

AggregationOperation matchByCpteAndDateValorisation =
    Aggregation.match(
        Criteria.where("numeroCompte")
            .is(numeroCompte)
            .and("dateValorisation")
            .gte(dateDebut)
            .lte(dateFin)
            .and("duration")
            .gte(0));

最后,这个解决方案对我有用