Skip to content

Creating a Type-Safe Query with Kotlin for Document IDs that have a relationship with DBRef #4713

Open
@sjiwon

Description

@sjiwon

Hello, I am developing based on Kotiln + Spring-Data-Mongo.

  • Spring Boot: 2.5.0
  • Java: 14
  • Kotlin: 1.7.0

I left an issue because I had a question while writing Mongo Type-Safe Query using Kotlin

@Document(collection = "origins")
data class Origin(
    @Id
    val id: String = ObjectId.get().toString(),
    @DBRef
    val ref: Ref,
)

@Document(collection = "refs")
data class Ref(
    @Id
    val id: String = ObjectId.get().toString(),
)

Let's assume there's a query like this

@MongoTest
class IssueTest(
    private val mongoTemplate: MongoTemplate,
) {
    @Test
    fun execute() {
        val dummyIds = listOf<ObjectId>(
            ObjectId("665ad0ac64d2bc76ec965e68"),
            ObjectId("665ad0ac64d2bc76ec965e6b"),
            ObjectId("665ad0ac64d2bc76ec965e6e"),
        )

        // QueryA
        var criteriaA = Criteria()
        criteriaA = criteriaA.and("ref.\$id").inValues(dummyIds)

        // QueryB
        var criteriaB = Criteria()
        criteriaB = criteriaB.and(Origin::ref / Ref::id).inValues(dummyIds)

        // execute
        println("===== CriteriaA =====")
        mongoTemplate.find<Origin>(Query(criteriaA))

        println("===== CriteriaB =====")
        mongoTemplate.find<Origin>(Query(criteriaB))
    }
}
===== CriteriaA =====
16:59:23.465 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - find using query: { "ref.$id" : { "$in" : [{ "$oid" : "665ad0ac64d2bc76ec965e68"}, { "$oid" : "665ad0ac64d2bc76ec965e6b"}, { "$oid" : "665ad0ac64d2bc76ec965e6e"}]}} fields: Document{{}} for class: ...

===== CriteriaB =====
16:59:23.481 [main] DEBUG o.s.data.mongodb.core.MongoTemplate - find using query: { "ref" : { "$in" : [{ "$oid" : "665ad0ac64d2bc76ec965e68"}, { "$oid" : "665ad0ac64d2bc76ec965e6b"}, { "$oid" : "665ad0ac64d2bc76ec965e6e"}]}} fields: Document{{}} for class: ...

The result I want is an inValues query for ref.$id like CriteriaA.

However, if use the Type-Safe Query provided by Spring-Data-Mongo + Kotlin, will get an inValues Query for ref document, not $id.

Is there a way to access ref.$id using Type-Safe Query?
Did this happen because of the low version?

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions