【问题标题】:Query in spring data mongo repository在spring数据mongo存储库中查询
【发布时间】:2017-10-02 09:14:26
【问题描述】:

我想在 Spring Data MongoDB 上编写自定义查询。像这样的:

public interface CarRepo extends MongoRepository<Car, String> {


  @Query("select distinct(brand) from Car ")
  public List<String> findDistinctBrand();
}

但它抛出错误“Caused by: com.mongodb.util.JSONParseException:”。我怎样才能做到这一点?

【问题讨论】:

  • 您在@Querypart 中提供sql 查询。这是完全错误的。对于 mongodbcheck this 的独特支持并检查 this 问题的答案以获取 spirng 数据部分
  • 但是在标准中我应该为给定的查询写什么(从 Car 中选择 distinct(brand))?

标签: java mongodb spring-boot


【解决方案1】:

MongoDB 不支持 distinct 命令。 它只支持使用distinct 命令返回不同的字段值。

您需要使用 Mongodb 模板来获取结果:

DBCollection colllection = mongoTemplate.getCollection("collectionName");
Criteria criteria = new Criteria();
criteria.where("your column").is("your value");
Query query = new Query();
query.addCriteria(criteria);
List list = mongoTemplate.getCollection("collectionName")
    .distinct("source",query.getQueryObject());

【讨论】:

  • this.mongoTemplate.getCollection("Car").distinct("brand") 这段代码对我有用。谢谢。
  • @yogi 如果字段源是 dbref,在这种情况下,它不起作用。我怎样才能得到 dbref 字段呢?
  • MongoTemplate 不需要查询不同的属性,请参阅:docs.spring.io/spring-data/mongodb/docs/current/reference/html/…
【解决方案2】:

你使用SQL在mongodb中查询,但是mongodb有自己的查询语言。您需要用该语言编写查询。当您要使用distinct 命令时,您不能使用Query 注释或弹簧数据查询来执行此操作。您需要创建自定义存储库并使用 MongoTemplate 执行不同的命令。

【解决方案3】:

根据the docs,您应该能够通过简单地在存储库接口中定义方法来完成此操作,而无需@Query 的帮助:

public interface CarRepo extends MongoRepository<Car, String> {
    public List<String> findDistinctBrand();
}

【讨论】:

  • 抛出异常Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findDistinctPublisher found for type News!
  • @fuat 那么你做错了什么。文档清楚地表明这是可行的,我自己也这样做了。
  • 我在存储库界面中做到了这一点 Set&lt;String&gt; findDistinctPublisher(); Publisher 是对象的一个​​属性。那么有什么问题吗?
猜你喜欢
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多