javaspringmongodbmongotemplate

Spring MongoDB: how to use DateOperators.DateDiff in ProjectionOperation


I have projection:

 ProjectionOperation projectionOperation = Aggregation.project()
                .and(DateOperators.DateFromString.fromString("$requiredDate")).as("requiredDate") //date
                .and(DateOperators.DateFromString.fromString("$currentDate")).as("currentDate") //date
                .and(DateOperators.DateDiff.diffValueOf("currentDate", "DAYS").toDateOf("requiredDate")).as("diff") //not working

I'm trying to retrive difference in days between currentDate and requiredDate, but last line end with error:

 org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 31325 (Location31325): 'Invalid $project :: caused by :: Unknown expression $dateDiff' on server localhost:60637. The full response is {"operationTime": {"$timestamp": {"t": 1706998440, "i": 2}}, "ok": 0.0, "errmsg": "Invalid $project :: caused by :: Unknown expression $dateDiff", "code": 31325, "codeName": "Location31325", "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1706998440, "i": 2}}, "signature": {"hash": {"$binary": {"base64": "AAAAAAAAAAAAAAAAAAAAAAAAAAA=", "subType": "00"}}, "keyId": 0}}}

In docs there is:

/**
 * Add the number of {@literal units} from a {@literal field} to a {@link #toDate(Object) start date}.
 *
 * @param fieldReference must not be {@literal null}.
 * @param unit must not be {@literal null}.
 * @return new instance of {@link DateAdd}.
 */
public static DateDiff diffValueOf(String fieldReference, String unit) {
    return diffValue(Fields.field(fieldReference), unit);
}

But I couldn't find any example on how to use this method. Unfortunately "unit" param is String, so I'm only guessing it's "DAYS", because there is no documentation and usage examples anywhere.


Solution

  • I think the correct approach is the following:

    .and(DateOperators.DateDiff
                              .diffValue("currentDate", "day")
                              .toDate("requiredDate").as("diff"));
    

    In the end it is going to be transformed to MongoQuery so the documentation here might help you a bit more.