Search code examples
javamongodbspring-bootaggregation-frameworkspring-data-mongodb

spring-data-mongodb : Check if a field is null or not exists in project filter stage


I have this stage in my aggregation pipeline, where I'm filtering the array elements where termination date is either null or doesn't exist.

{
    "$project": {
        "_id": 1,
        "name": 1,
        "versions": {
            "$filter": {
                "input": "$versions",
                "as": "v",
                "cond": {
                    "$lte": [
                        "$$v.terminationDate", null
                    ]
                }
            }
        }
    }
}

This works fine in Mongo shell. MongoPlayGround

But, I'm not sure how to write this in spring-data-mongodb.

Aggregation.project()
    .andInclude("name")
    .and(Filter.filter("versions")
        .as("v")
        .by(ComparisonOperators.valueOf("$$v.terminationDate").lessThanEqualToValue(null)))
    .as("versions");

But, lessThanEqualToValue doesn't accept null.

Please help.


Solution

  • I think this could works. The goal is to reproduce this query using $ifNull so you can try something like this:

    Updated with the small change from the comments to works perfectly:

    Aggregation.project()
        .andInclude("name")
        .and(Filter.filter("versions")
            .as("v")
            .by(ComparisonOperators.valueOf(ConditionalOperators.ifNull("$$v.terminationDate")
                    .then(true)).equalToValue(true))
        .as("versions");