I want to transform the below-given code to java code:
db.cabinetStatusInfo.aggregate([
{
$project: {
"fullPowerCount": 1,
"cabinCount": 1,
"fullPowerWarn": 1,
"cabinetId": 1,
"difference": {
$cond: {
if : { $eq: ["$cabinCount", null] },
then: true,
else : {
$gte: [
{ $multiply: [
{ $toInt: { $ifNull: [ "$fullPowerCount", 0 ] } }, 5
] }
,
{ $toInt: "$cabinCount" }
]
}
}
}
}
},
{
$match: {
difference: true
}
}
]);
I don't know how to use $multiply
. Spring data's MongoDB documentation shows how to multiple a Field multiply a number, but does not show how to make the expression multiply with a number. Can you help me?
Aggregation aggregation = newAggregation(project("fullPowerCount", "cabinCount")
.and("difference")
.applyCondition(ConditionalOperators.Cond.newBuilder()
.when(Criteria.where("cabinetCount").is(null))
.then(true)
.otherwise(
//how to use $multiply,help me
(toInt(ifNull("fullPowerCount").then('0'))) )
),
match(Criteria.where("diffrence").is(true))
);
Thank you very much!
First, I am changing the following code snippet from your aggregation and what I feel is the correct way (the functionality is same). This is in the aggregation query's $project
stage's if
statement.
This is your code:
"difference": {
$cond: {
if : { $eq: ["$cabinCount", null] },
The if
clause is changed to:
if : { $eq: [ { $type: "$cabinCount" }, "null" ] },
This is because, though your code will work in mongo
shell, it is difficult to convert into Spring Data MongoDB code (it takes more code and is complex). Note the null
in MongoDB data is different from null
in Java - there is no direct conversion. Null cannot be specified as it is in Java.
The transformed code:
ConditionalOperators.Cond conditon =
ConditionalOperators.Cond.newBuilder()
.when(
ComparisonOperators.Eq.valueOf(
DataTypeOperators.Type.typeOf("cabinCount"))
.equalToValue("null")
)
.then(Boolean.TRUE)
.otherwise(
ComparisonOperators.Gte
.valueOf(
ArithmeticOperators.Multiply.valueOf(
ConvertOperators.Convert.convertValueOf(
ConditionalOperators.IfNull.ifNull("fullPowerCount").then(Integer.valueOf(0))
).to("int")
)
.multiplyBy(Integer.valueOf(5))
)
.greaterThanEqualTo(
ConvertOperators.Convert.convertValueOf("cabinCount").to("int")
)
);
Aggregation agg = newAggregation(
Aggregation.project("cabinCount", "fullPowerCount")
.and(
condition
)
.as("difference")
);
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testDB");
AggregationResults<Document> results = mongoOps.aggregate(agg, "testColl", Document.class);