我想在spring数据mongodb上编写自定义查询 . 像这样的东西:
public interface CarRepo extends MongoRepository<Car, String> {
@Query("select distinct(brand) from Car ")
public List<String> findDistinctBrand();
}
但它正在抛出错误“ Caused by: com.mongodb.util.JSONParseException:
” . 我怎样才能做到这一点?
3 回答
MongoDB不支持distinct命令 . 它仅支持使用distinct命令返回不同的字段值 .
您需要使用Mongodb模板,以获得结果:
根据the docs,您应该能够通过简单地在存储库界面中定义方法来实现此目的,而无需
@Query
的帮助:您正在使用
SQL
在mongodb中查询,但mongodb有自己的查询语言 . 您需要使用该语言编写查询 . 当您打算使用distinct
命令时,您无法使用Query
注释或 spring 数据查询来执行此操作 . 您需要使用MongoTemplate
创建自定义存储库并执行distinct命令 .