일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- spring mongoTemplate switch
- rabbitmq 싱글톤
- 전략 패턴이란
- 익명 객체 @transactional
- ipfs bean
- java 파티
- 자바 백준 팩토리얼 개수
- Java Call By Refernce
- kotiln functional interface
- go
- 백준 연결요소 자바
- java 팩토리얼 개수
- mongodb lookup
- kotiln const
- java 백준 1509
- 백준 1504 java
- 백준 특정한 최단 경로
- spring mongodb
- 자바 1676
- spring mongoTemplate
- java 1509
- Spring ipfs
- nodejs rabbitmq
- java 1238
- kotiln const val
- 안정해시
- javav 1676
- spring mongodb switch
- ipfs singletone
- 백준 2252 줄세우기
Archives
- Today
- Total
공부 흔적남기기
Spring mongodb mongoTemplate project stage에서 switch 사용하기 본문
web study/Spring
Spring mongodb mongoTemplate project stage에서 switch 사용하기
65살까지 코딩 2023. 11. 28. 21:47728x90
반응형
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
반응형
'web study > Spring' 카테고리의 다른 글
프록시 팩토리 | Advice | Pointcut (0) | 2023.12.20 |
---|---|
Spring Scheduler SchedLock MongoDB 설명 및 구현 (0) | 2023.12.01 |
Intelij gradle 'compilejava' task (current target is 11) and 'compilekotlin' task (current target is 1.8) jvm target compatibility should be set to the same java version. error (0) | 2023.11.23 |
Sppring IPFS CLIENT 싱글톤으로 사용시 주의점 (0) | 2023.11.16 |
스프링 json 직렬화의 함정 (is가 prefix일 경우 사라짐) (0) | 2023.03.16 |