Alex Paransky
Alex Paransky

Reputation: 305

How to create count query on MongoRepository

I am creating a MongoRepository and need to create a count query. Can someone provide an example of what is the best way to do this via the SpringData MongoDB MongoRepository facility? All the examples I was able to find reference returning a List but not counts.

Here is what I am trying to do (obviously it does not work):

public interface SchoolRepository extends MongoRepository<School, String> {
    @Query("db.school.count({studentStatus: ?0});")
    int getCountOfStudents(int studentStatus);
}

Thanks. -AP_

Upvotes: 2

Views: 2095

Answers (1)

Anonymoose
Anonymoose

Reputation: 5982

I found this question as I was trying to do something similar. Unfortunately, given what I see in org.springframework.data.repository.query.parser.PartTree:

private static final Pattern PREFIX_TEMPLATE = Pattern.compile("^(find|read|get)(\\p{Upper}.*?)??By");

It does not appear to be supported.

Instead, we can add custom behaviour to the repository (see reference manual section 1.4.1) by creating a new interface and a class that implements it.

public interface SchoolRepository extends CrudRepository<School, String>, SchoolRepositoryCustom {
    // find... read... get...
}

public interface SchoolRepositoryCustom {
    int getCountOfStudents(int studentStatus);
}

@Service
public class SchoolRepositoryImpl implements SchoolRepositoryCustom {
    @Autowired
    private SchoolRepository schoolRepository;

    public int getCountOfStudents(int studentStatus) {
        // ...
    }
}

Note that the class is named SchoolRepositoryImpl, not SchoolRepositoryCustomImpl.

Upvotes: 1

Related Questions