데이터베이스/MongoDB
Spring data mongo CustomAggregation Invalid reference 트러블 슈팅
65살까지 코딩
2023. 2. 14. 21:40
728x90
반응형
spring data mongo에서 지원하는 Agggregation에서 $lookup operation은 from, localfield, foreinfield, as로 한정적이다.
따라서 collection의 한가지 field로만 join하여 사용할 수 있다.
하지만 필자는 2가지 이상의 필드를 이용하여 join할 필요가 있어 CustomAggregation 만들어 사용했다.
import org.bson.Document
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext
import org.springframework.data.mongodb.core.aggregation.ExposedFields
import org.springframework.data.mongodb.core.aggregation.Fields
import org.springframework.data.mongodb.core.aggregation.FieldsExposingAggregationOperation
class CustomAggregationOperation(
private val operation: Document
) : AggregationOperation {
@Deprecated("Deprecated in Java")
override fun toDocument(context: AggregationOperationContext): Document {
return context.getMappedObject(operation)
}
}
처음에는 다음과 같이 AggergationOperation을 상속받아 Document를 이용하여 Aggregation을 진행하였다.
진행하는 도중 lookup후 생겨야할 필드 즉 as로 지정한 필드가 Aggregation().project로는 접근이 되지 않고 오직 Document 형식으로만 접근이 가능했다.
spring data mongo를 살펴보고 구글링한 결과 ExposedFields에 data가 들어가지 않음이 확인 되었다. 원인은 자세히 파악하지 못했다.
해결책으로는
import org.bson.Document
import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext
import org.springframework.data.mongodb.core.aggregation.ExposedFields
import org.springframework.data.mongodb.core.aggregation.Fields
import org.springframework.data.mongodb.core.aggregation.FieldsExposingAggregationOperation
class CustomAggregationOperation(
private val operation: Document
) : FieldsExposingAggregationOperation.InheritsFieldsAggregationOperation {
@Deprecated("Deprecated in Java")
override fun toDocument(context: AggregationOperationContext): Document {
return context.getMappedObject(operation)
}
override fun getFields(): ExposedFields {
return ExposedFields.synthetic(Fields.fields("result", "\$\$value", "\$\$this"))
}
}
해결책으로는 다음과같이 Field를 Expose시킬수 있는 AggregationOperation을 상속 받아 미리 데이터를 노출시키는 방식으로 해결 하였다.
728x90
반응형