mongodbspring-bootaggregation-frameworkspring-data-mongodbcriteria

ConditionalOperators return null in else case throws exception


I have below code to map the fields with projection.

  private static ProjectionOperation getProjectionOperation() {
      
      Cond conditional =  ConditionalOperators.when(Criteria.where("joined.isHeaderDocument").is(Boolean.TRUE)).thenValueOf("documentID").otherwise(null);
        ProjectionOperation projectOperation = Aggregation.project(
                 .and("doc").as("relationshipNumber") 
                 .and(conditional).as("headerForm");
                 
                
        return projectOperation;

I have to return documentID value when isHeaderDocument is true otherwise i should not map the field "headerForm" . I am getting exception like "null values not supported for conditional operators". Can any on please help


Solution

  • otherwise needs a non null parameter, which is why you are seeing this error.

    Instead of assigning null to the field, what you need to do is to remove the field when condition is not met using $$REMOVE. Your native query should be

    {
        "$cond": {
            "if": {"$eq": ["$joined.isHeaderDocument", true]}, 
            "then": "$documentID", 
            "else": "$$REMOVE"
        }
    }
    

    Springboot:

    Cond conditional = ConditionalOperators.when(
                    Criteria.where("joined.isHeaderDocument").is(Boolean.TRUE))
                    .thenValueOf("documentID").otherwise(Aggregation.REMOVE);