在 Spring Data MongoDB 存储库中计数

2022-01-18 00:00:00 mongodb spring java spring-data

我想知道是否有任何机制可以在 Spring Data MongoDB 存储库中使用 count@Query 注释?我很想收到我所拥有的文件数量,而不必获取所有文件.

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.

基本上相当于Java中的this:

Basically, the equivalent of this in Java:

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

推荐答案

对我来说,这个解决方案就像一个魅力(使用 spring-data-mongodb 1.3.1.RELEASE ),我刚刚遇到了同样的问题并像这样解决了它(只是我工作代码中的一小段):

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);

相关文章