EzyMongo: Custom Query Result

Updated at 1691028385000
In a aggregate query, sometimes you don't want to select entire entity. EzyMongo will help you map query result to a result class.

1. Query

Let's say we have an entity class and a query method like this:

    @Getter
    @Setter
    @ToString
    @EzyCollection("test_mongo_duck")
    @NoArgsConstructor
    @AllArgsConstructor
    public class Duck {
        @EzyCollectionId(composite = true)
        private DuckId id;
        private int age;
        private String description;
    }
    

    @EzyQuery(
        "[" +
        "{ $sort: { id: 1 }}," +
        "{ $match: { age: ?0 }}, " +
        "{ $project: { age: 0 } }" +
        "]"
    )
    DuckResult fetchDuckByAge(
        int age
    );

Let's focus on { $project: { age: 0 } }, we don't want to select age field.

2. Result class

With 2 above Duck class and ignored age field, we will need create a class with 2 fields:

    @Data
    @EzyQueryResult
    @NoArgsConstructor
    @AllArgsConstructor
    public class DuckResult {
        private DuckId id;
        private String description;
    }

Don't for get @EzyQueryResult annotation, EzyMongo will need this annotation to recognize the result class and create deserializer class for it.

3. Use cases

You can use request class in 3 cases:

  • Find one nullable result, example: DuckResult fetchDuckByAge
  • Find one optional result, example: Optional<Duck> fetchDuckByAgeOptional
  • Fine a list result, example: List<Duck> fetchDuckByAgeList

4. An another way to fetch some fields

If you don't want to use aggregate, you can use find method with the entity, example:

    @EzyQuery("{$query: {age: {$gte : ?0}}, $fields: ['id', 'age'], $orderBy : {age: -1}}")
    List<Duck> findListDuckSomeFields(int age, Next next);

In this case, unselected fields will be default value.

Next

You can see how to connect to multi databases.