Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count in Spring Data MongoDB repository

Tags:

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  
like image 378
paul Avatar asked May 23 '13 13:05

paul


People also ask

What is @document annotation in Spring boot?

@Document is an annotation provided by Spring data project. It is used to identify a domain object, which is persisted to MongoDB. So you can use it to map a Java class into a collection inside MongoDB. If you don't use Spring Data, you don't need this annotation.

Which is better MongoTemplate or MongoRepository?

So I'd say that MongoTemplate is a better option, unless you have a very elaborated POJO model or need the custom queries capabilities of MongoRepository for some reason. Good points/examples. However your race condition example and undesired result can be avoided using @Version to prevent that very scenario.

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.


1 Answers

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

like image 127
DanJ Avatar answered Oct 06 '22 07:10

DanJ