How to use aggregate addFields using Java driver?

Need help with java driver aggregation pipeline stage to add a field based on a field derived in earlier stages.

$addField: 
{
  transientloadIndex: {
    $cond: [ 
      { $gte: [ "$batchWindowSessionCount", 3 ] },
      1, 
      0 
      ]
  }
}

.
.
.

 Aggregates.addFields(new Field("transientloadIndex", ConditionalOperators.when(Criteria.where("$batchWindowSessionCount").gte(batchSize)).then(1).otherwise(0))),

.
.
.

Getting following error with above:

com.mongodb.MongoCommandException: Command failed with error 40180 (Location40180): ‘Invalid $addFields :: caused by :: an empty object is not a valid value. Found empty object at path transientloadIndex’ on server localhost:27017. The full response is {“ok”: 0.0, “errmsg”: “Invalid $addFields :: caused by :: an empty object is not a valid value. Found empty object at path transientloadIndex”, “code”: 40180, “codeName”: “Location40180”}

Can someone please help with what I am missing here? Thanks!

Hello @Abhishek_Kumar_Singh, the method Aggregates.addFields is from the Java Driver APIs, but you are also using the Spring Data MongoDB API ConditionalOperators.when(Criteria.where... within it. That will not work. You need to use only one of them for writing the query.

Some references about using the aggregation queries with Java driver:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.