Distinct in Spring Data MongoDB

mongodb distinct
mongodb distinct query java
spring data mongodb inheritance
spring data mongodb join query
spring data mongodb like query
mongodb distinct limit
spring data mongodb repository projection
spring data mongodb aggregation count

Has anyone tried incorporating distinct in their query using Spring Data for Mongo. If you have an example can you please post it. Where and how should I include the distinct flag?

Link to the Spring Data Mongo example -- Example 4.4. Query creation from method names

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

After a little poking around, I have come up with the following solution, which is OK and works, but can probably be improved upon. I am still pretty new to Spring, so if you have a better idea, then please do let me know.

Anyway, here it is:

First off, we use the @Autowired annotation to bring in the base MongoTemplate from spring-data-mongodb

@Autowired
MongoTemplate mongoTemplate;

Once we have that, we can use it to make some queries. Note that this is the slightly smelly part because you have to tell Spring what the return type is and it doesn’t really like that…

// Get the distinct stuff from MongoDB
List<String> coll = mongoTemplate.getCollection("mycollection").distinct("myfield");

In the above code you will notice that I have defined a List type variable called coll that uses the @Autowired MongoTemplate variable to get a collection and then a field using distinct. This is analogous to db.whatever.distinct("term") on the Mongo shell.

MongoDB distinct example using Spring data, This mongoDB and Spring data tutorial will help you to finds the distinct values for a specified field from defined collection or document and  MongoDB distinct example using spring data. By Yashwant Chavan, Views 105659, Last updated on 20-Feb-2019. This mongoDB and Spring data tutorial will help you to finds the distinct values for a specified field from defined collection or document and returns the respected result set in an array format.

My environment: spring-data-mongodb 2.0.5,jdk1.8,

Here is my code sample:

import com.mongodb.client.DistinctIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;


public List<String> queryAllCategory() {
    List<String> categoryList = new ArrayList<>();
    MongoCollection mongoCollection = mongoTemplate.getCollection("lexicon");
    DistinctIterable distinctIterable = mongoCollection.distinct("category",String.class);
    MongoCursor cursor = distinctIterable.iterator();
    while (cursor.hasNext()) {
        String category = (String)cursor.next();
        categoryList.add(category);
    }
    return categoryList;
}

about distinct method,please read: http://mongodb.github.io/mongo-java-driver/3.7/javadoc/com/mongodb/client/MongoCollection.html#distinct-java.lang.String-java.lang.Class-

Spring Data MongoDB, For information on the Spring Data Mongo source code repository, nightly builds and String lastname); // Enables the distinct flag for the query List<Person>  Starting in MongoDB 4.2, if the client that issued the db.collection.distinct() disconnects before the operation completes, MongoDB marks the db.collection.distinct() for termination (i.e. killOp on the operation).

Currently MongoDB does not support to retrieve documents in a distinct way. It only supports returning distinct field values using the distinct command.

As it is apparently the latter you're looking for, the bad news is, we currently don't support any projections in derived queries. For progress on this, please follow the related JIRA ticket.

com.mongodb.client.MongoCollection.distinct java code examples , DistinctIterable iterable = collection.distinct(mappedFieldName, origin: spring-​projects/spring-data-mongodb MongoDbMessageStore.iterator(). @Override  distinct ReactiveFindOperation.TerminatingDistinct < Object > distinct( String field) Finds the distinct values for a specified field across a single MongoCollection or view.

You can see the differences of the usage of distinct between Spring Data JPA and Spring Data MongoDB here:

@Before
public void setUp() {

    this.dave = customers.save(new Customer("Dave", "Matthews"));
    this.carter2 = customers.save(new Customer("Carter", "Z"));
    this.carter = customers.save(new Customer("Carter", "Beauford"));
}

@Test
public void distinctProjectsEntityIntoInterface() {

    Collection<CustomerProjection> result = customers.findAllProjectedDistinctBy();

    assertThat(result, hasSize(2));
}

distinct in spring data jpa

@Before
public void setUp() {

    customers.deleteAll();

    this.dave = customers.save(new Customer("Dave", "Matthews"));
    this.carter2 = customers.save(new Customer("Carter", "Z"));
    this.carter = customers.save(new Customer("Carter", "Beauford"));
}

@Test
public void distinctProjectsEntityIntoInterface() {

    Collection<CustomerProjection> result = customers.findAllProjectedDistinctBy();

    assertThat(result, hasSize(3));
}

distinct in spring data mongodb

where

interface CustomerProjection {

    String getFirstname();
} 

MongoDB distinct Query, Has anyone tried incorporating distinct in their query using Spring Data for Mongo . If you have an example can you please post it. Where and  Spring Data MongoDB: Projections and Aggregations 1. Overview. Spring Data MongoDB provides simple high-level abstractions to MongoDB native query 2. Projection. In MongoDB, Projections are a way to fetch only the required fields 3. Aggregation. Aggregation in MongoDB was built to process

Lot has changed since this question was posted. Answering my own question as this question keeps popping up.

Support is there since 3.0 and higher

public DistinctIterable<String> getUniqueTask() {
    return mongoTemplate.getCollection(TABLE).distinct("FIELD", String.class);
}

Side Note: You can even add filters/regex to this query. Read docs. If you cannot find, ping, will post the answer.

Retrieve distinct values for field in MongoDB collection, Spring Data MongoDB. MongoDB distinct method returns a set of discrete values for the field specified as the input argument. Mongo distinct method returns an  MongoDB distinct Query. MongoDB distinct method returns a set of discrete values for the field specified as the input argument. Mongo distinct method returns an array of discrete values. Table of Contents [ hide] 1 MongoDB distinct. 1.1 MongoDB distinct Java Program.

mongodb, Connect to MongoDB and retrieve a distinct set of values for a field in a The cell array can contain numeric scalars for numeric data, character vectors for text​  The Spring Data MongoDB project applies core Spring concepts to the development of solutions that use the MongoDB document style data store. We provide a “template” as a high-level abstraction for storing and querying documents. You may notice similarities to the JDBC support provided by the Spring Framework.

A Guide to Queries in Spring Data MongoDB, Hat jemand versucht, distinct mit Spring Data for Mongo in seine Abfrage einzubeziehen? Wenn Sie ein Beispiel haben, können Sie es bitte posten. Wo und wie  One of the more common ways to query MongoDB with Spring Data is by making use of the Query and Criteria classes – which very closely mirror native operators. 2.1.

Spring Data Mongo - Query methods and Distinct field, How to Query MongoDB with Spring Data: Query and Criteria, auto-generated repository methods, raw queries with the @Query annotation as  Spring Data MongoDB focuses on storing data in MongoDB. It also inherits functionality from the Spring Data Commons project, such as the ability to derive queries. Essentially, you need not learn the query language of MongoDB. You can write a handful of methods and the queries are written for you.

Comments
  • Thats interesting. Will give it a try.
  • Thanks, it worked well for me! We just have to keep in mind that it has a limitation in result size, check their docs: docs.mongodb.com/manual/reference/method/db.collection.distinct/…
  • @paulscott56 Is there anyway I can use a Query before I get distinct values for a field? Like, I want to get distinct values only when x=1, how can provide that criteria?
  • Could you please guide here: stackoverflow.com/questions/55535331/… ?
  • This worked for me, remember to have the 2nd argument be the type of the property you are extracting. I thought at first List.class would be a working solution - but that does not work.
  • Oliver I appreciate you responding. Really appreciate what you are doing. I am not looking for distinct document but distinct field values. Though MongoDB query supports distinct I could not find Spring Data supporting this feature in its query. Simple scenario I can think of - Lets say there are X users from different countries. Can I have distinct countries listed for all the users. BTW I am using @DBRef if thats could be considered as Join, but thats off topic and yes your are right individual documents are distinct.
  • I was able to solve the issue by using java.util.Set. Would be nice if I could set the distinct requirement in the Query.
  • @Oliver Drotbohm - Do we've distinct feature for Query now ?
  • @java_dude - Could you please post your answer ? How did you solved this?
  • @PAA I have posted my solution. HTH
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
  • @H. DJEMAI Thanks for the review, I've changed it.