The document on which the aggregation is being run on has the following structure.
{
"field1" : "value1",
"field2" : "value2",
"field3" : "value3"
}
along with other irrelevant fields for the current scenario. Note that type of values in field1, field2, field3 are all of type strings.
WORKING SCENARIO:
The aggregation has one projection Operation after which the desired output structure of the final document is as follows:
{
"field4" : {
"field5" : "value1",
"field6" : "value2",
"field7" : "value3"
}
}
Able to achieve this with the below query in mongo Db shell:
db.getCollection("testCollection").aggregate(
[{
"$project": {
"field4": {
"field5": "$field1",
"field6": "$field2",
"field7": "$field3"
}
}
}]
)
In spring data mongo terms, able to achieve this with the below code:
Aggregation.project()
.nested(Fields.from(Fields.field("field5", "field1"),
Fields.field("field6", "field2"),
Fields.field("field7", "field3")))
PROBLEM SCENARIO
The requirement now is that if any of the values in field1, field2, or field3 is null, then they get a default value.
Able to achieve this with the below query in mongo Db shell:
db.getCollection("testCollection").aggregate(
[{
"$project": {
"field4": {
"field5": {"$ifNull" :["$field1", ""]},
"field6": {"$ifNull" :["$field2", ""]},
"field7": {"$ifNull" :["$field3", ""]}
}
}
}]
)
But, when trying to achieve the same in spring data mongo terms, not able to achieve the same.
What has been tried so far:
Aggregation.project()
.nested(Fields.from(Fields.field("field5",
ConditionalOperators.ifNull("field1").then(StringUtils.Empty)),
Fields.field("field6", "field2"),
Fields.field("field7", "field3")))
but this throws an error saying that the second argument to the Fields.field should be of type java.lang.string, but found ConditionalOperators.ifNull.
So, what is the right way to achieve the mongo db query in spring data mongo db terminology?