Marcin Psyk Marcin Psyk - 4 months ago 42
Java Question

MongoDB Distinct with condition in Java

Is there any possibility to implement MongoDB distinct with condition, like this below, but with Java driver?

db.orders.distinct( 'ord_dt', { price: { $gt: 10 } } )


I have tried with
MongoRepository
, like below

// Enables the distinct flag for the query
List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);

List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);


But in my opinion it is not working correctly. I have also tried
MongoTemplate


mongoTemplate.getCollection("mycollection").distinct("myfield")


But there is no way to implement condition. Any idea how to solve that?

Best regards

Answer

Spring MongoTemplate has inbuilt support for distinct with query:

mongoTemplate.getCollection("collection_name").distinct("field", new BasicDBObject("price", new BasicDBObject("$gt", 10)));

Comments