paul
paul

Reputation: 13471

Count in Spring Data MongoDB repository

I wonder if there's any mechanism to use count in Spring Data MongoDB repository with @Query annotation? I would love to receive the number of documents that I have without having to get all of them.

Basically, the equivalent of this in Java:

db.test.find({"type":"foo"}).count 

Upvotes: 28

Views: 50119

Answers (3)

DanJ
DanJ

Reputation: 1756

Another way to do this using MongoRepository query templates:

public interface MyRepository extends MongoRepository<MyClass, String> {
    Long countByLastname(String lastname);
}

See http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#repositories.query-methods.details

Upvotes: 69

wmax
wmax

Reputation: 1064

For me this solutions works like a charm( using spring-data-mongodb 1.3.1.RELEASE ), I just had the same problem atm and solved it like this(just a short snippet from my code at work):

@Query(value = "{'productDetails.productType': {$regex: ?0, $options: 'i'}, 'sourceDescriptor': ?1}", count = true)
public Long countFetchedDocumentsForCategory(String cat, String sourceDescriptor);

Upvotes: 58

Maciej Walkowiak
Maciej Walkowiak

Reputation: 12932

I had same problem recently and unfortunately did not find any solution at least not with current stable version. It seems that it is possible in Spring Data JPA 1.4M1 so maybe it will be also included in next version of Spring Data MongoDB.

Upvotes: 2

Related Questions