공부 흔적남기기

Spring mongodb mongoTemplate project stage에서 switch 사용하기 본문

web study/Spring

Spring mongodb mongoTemplate project stage에서 switch 사용하기

65살까지 코딩 2023. 11. 28. 21:47
728x90
반응형

How to use switch case on spring mongo data mongotemplate

 

프로젝트에서 mongodb를 사용하는데 

project시 분기를 태워서 나타내야하는 field가 존재했다. 
예를들어 

 student {

id: ObjectId,

name: String,

stauts: int,

} 이라는 객체가 있다고 가정하자 

status가
0일때 ABSENT,
1 일때 ATTENDANCE,
-1 일떄 FIRE 로 표현해야한다. 

물론 data를 그냥 받아서 for문을 돌려서 바꿔줄 수 있지만 project를 통해 충분히 구현이 가능하고 성능으로 봐도 더 좋을 것이라 생각했다. 
mogodb stage에서는 아주 간단했다.
이곳을 참조하면 쉽게 구현할 수 있다.  https://www.mongodb.com/docs/manual/reference/operator/aggregation/switch/

 

$switch (aggregation) — MongoDB Manual

Docs Home → MongoDB Manual $switchEvaluates a series of case expressions. When it finds an expression which evaluates to true, $switch executes a specified expression and breaks out of the control flow.$switch has the following syntax:$switch: { branches

www.mongodb.com

이것을 Spring data mongo의 mongoTemplate에서 어떻게 사용할지가 고민이 되었다.  구글링을 해보거나 GPT에게 시켜보았을 때 마땅히 Project와 swtich에 대한 내용이 없거나 틀리고 Document 단으로 내려가는 코드가 많아 작성하게되었다.

Project에서  ConditionalOperators.switchCases 라는 operator를 지원하길래 순조롭게 진행 될 줄 알았으나 CaseOperator.`when`()의 인자의 type이 Criteria가 아닌 AggregationExpression이여서 애좀 써서 코드를 작성했다.

 Aggregation.project().and(
                ConditionalOperators.switchCases(
                    CaseOperator.`when`(ComparisonOperators.valueOf("status").equalTo(ToInt.toInt("0"))).then("ABSENT"),
                    CaseOperator.`when`(ComparisonOperators.valueOf("status").equalTo(ToInt.toInt("1")))
                        .then("ATTENDANCE"),
                    CaseOperator.`when`(ComparisonOperators.valueOf("status").equalTo(ToInt.toInt("-1")))
                        .then("FILRE"),
                ).defaultTo("ABSENT")

 

건승을 빕니다.

728x90
반응형