I cannot figure to multiple fields by using $addFields
for if else condition in MongoDB with Java operator. My requirement is to add Mutiple fields based of if else condition. I know how to add multiple fields bu using $addFields
and $project
but not with if else condition.
Can anyone help me how to implement in Java with MongoDB operators?
Appreciate any help. Thanks in advance.
$addFields syntax:
.append(system, new Document()
.append("$cond", new Document()
.append("if", new Document()
.append("$eq", Arrays.asList(
"$system",
"AA"
)
)
)
.append("then", new Document()
.append("value.amount", new Document()
.append("$multiply", Arrays.asList(
"$value.amount",
Decimal128.parse("-1.0")
)
)
)
.append("value2", new Document()
.append("$multiply", Arrays.asList(
"$value.amount",
Decimal128.parse("-1.0")
)
)
)
)
$project :
new Document()
.append("$project", new Document()
.append("_id", 0.0)
.append("value.amount", 0.0)
.append(sourceSystem, new Document(
"$cond", new Document(
"if", new Document("$eq", "true") )
)
.append("then", new Document()
.append("original.amount", 0.0)
.append("amount.amount", 0.0)
)
pseudo-code:
"$addFields" : {
'system.amount':'$_id',
"system.amount1" : Period,
{"system": "AA",
"amount" : {
"$multiply" : [
"$amount",
-1.0
]
},
"amount1" : {
"$multiply" : [
"$.amount1",
-1.0
]
},
"amount2" : {
"$multiply" : [
"$amount2",
-1.0
]
},
}
{"system": "BB",
"amount3" : {
"$multiply" : [
"$amount3",
-1.0
]
},
}
},
2
Answers
We can use $arrayToObject operator.
Main idea: We create an array structure of fields we need (operator format), convert it to an object, and reshape the final result.
If you comment pipeline steps (from backwards), you can observe how we reshape documents.
MongoPlayground | All in 1 step