user8218712
user8218712

Reputation:

Query in spring data mongo repository

I want to write custom query on spring data mongodb. Something like this:

public interface CarRepo extends MongoRepository<Car, String> {


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

But it's throwing an error "Caused by: com.mongodb.util.JSONParseException: ". How can I achieve that?

Upvotes: 0

Views: 3329

Answers (3)

Madbreaks
Madbreaks

Reputation: 19539

Per the docs you should be able to accomplish this by simply defining the method in your repository interface, without the help of @Query:

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

Upvotes: -1

Yogi
Yogi

Reputation: 1895

MongoDB does not support distinct command. It only supports returning distinct field values using the distinct command.

You need to use Mongodb template, for your results:

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

Upvotes: 3

Ruben Vardanyan
Ruben Vardanyan

Reputation: 1308

You are using SQL to query in mongodb, but mongodb has its own query language. You need to write query in that language. As you are going to use distinct command you cannot user Query annotation or spring data query to do that. You need to create custom repository and execute distinct command using MongoTemplate.

Upvotes: -1

Related Questions