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
@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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With