tzortzik
tzortzik

Reputation: 5143

spring data mongodb querying nested objects and nested objects performance

I have the following mongodb document structure and I have a few questions about it:

[{
        "_id" : ObjectId("5a9ad6935625732968b720a6"),
        "customer" : {
                "_id" : ObjectId("5a9ab4b6acf09dde448e0348"),
                "email" : "...",
        },
        "pType" : {
                "_id" : ObjectId("5a9ab4b6acf09dde448e033a"),
                "name" : "..."
        },
        "dateTimeCreated" : ISODate("2018-03-03T17:08:35.351Z"),
        "_class" : "..."
}]

1. What I currently want to do is to select all documents that have a specific Customer ID

I tried with

@Repository
interface CustomerPassRepo : ReactiveMongoRepository<CustomerPtype, String> {

    @Query(value = "{ 'customer.id' : ?0 }")
    fun findAllByCustomerId(id: String) : Flux<CustomerPtype>

    @Query(value = "{ 'customer._id' : ?0 }")
    fun findAllByCustomerId1(id: String) : Flux<CustomerPtype>

    fun findAllByCustomer_Id(id: String) : Flux<CustomerPtype>

    fun findAllByCustomer_id(id: String) : Flux<CustomerPtype>

}

None worked.

2. Does this type of schema impact the query performance? I mean is the first approach slower than

[{
        "_id" : ObjectId("5a9ad6935625732968b720a6"),
        "customerId" : {
                "_id" : "5a9ab4b6acf09dde448e0348",
                "email" : "...",
        },
        "pTypeId" : "5a9ab4b6acf09dde448e033a",
        "dateTimeCreated" : ISODate("2018-03-03T17:08:35.351Z"),
        "_class" : "..."
}]

The first approach is taking much more space but it's better because I do not need to join the data later. The first approach is duplicating the customer and pType.

3. Any other suggestions?

Upvotes: 2

Views: 4064

Answers (2)

Saneesh Jose
Saneesh Jose

Reputation: 1

You can get this done by using the following method

BaseClassObject findByCustomer__id(String customerId)

You have to separate the parameters by an underscore in order to access the objects of the nested class

Upvotes: 0

tzortzik
tzortzik

Reputation: 5143

I found a solution somewhere which says that I should use ObjectId as method paramter.

All of the following worked:

@Query(value = "{ 'customer.id' : ?0 }")
fun findAllByCustomer_Id(objectId: ObjectId) : Flux<CustomerPass>

@Query(value = "{ 'customer.id' : ?0 }")
fun findAllByCustomer(objectId: ObjectId) : Flux<CustomerPass>

@Query(value = "{ 'customer._id' : ?0 }")
fun findAllByCustomer(objectId: ObjectId) : Flux<CustomerPass>

Still not elegant but it is working. I a still looking for answers or alternative solutions.

Source: https://stackoverflow.com/a/34169761/869793

Upvotes: 1

Related Questions