简体   繁体   中英

Mongo Pojo with Spring boot, how to fetch subset of data in a document

I have a spring boot application setup to work with Mongo data Pojo. I have the following dependencies among other things (I have excluded Jackson, and am using Gson instead) -

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- Exclude the default Jackson dependency -->
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
        </exclusion>
    </exclusions>
</dependency>

I have 2 classes, both referring to the same collection. The only difference is that ModuleB has some fields missing -

@Document("Module")
class ModuleA extends MongoModel{
    int X = 0;
    String Y = "something";
}


@Document("Module")
class ModuleB extends MongoModel{
    String Y = "something";
}

I am using MongoTemplate to get the data -

protected final MongoTemplate template;
@Override
public MongoModel get(Class<? extends MongoModel> cls, Query query) {
    query.addCriteria(Criteria.where("deleted").is(0));
    return template.findOne(query, cls);
}

Now, when I use spring repository to get an instance/document of ModuleA or ModuleB, is there going to be a performance difference (or query difference) in the select operation that is performed by spring-boot? Or does spring-boot gets all the fields in both cases anyways, and then populates the object with required fields.

The example above may seem trivial, but if I have many fields or DBRef to another document inside the Module, I can save significant processing when fetching a subset of data instead of fetching the entire document.

For maintainability and consistency, you shouldn't use multiple @Document-annotated models referring to the same MongoDB collection.

It can get really messy if one model has eg different @Index annotations or datatypes, or you use one model to insert and another model to read or update.

For read-only operations those problem do not occur, but then you don't need a @Document annotation anyway, you can use projections , as mentioned by @prasad_.

You should keep the projections together with the core domain model, so in the future you don't forget to eg rename a field in the projection after you renamed it in the core domain model etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM