Skip to content
Advertisement

How to write a query to get distinct values from mongodb collection?

I need to get distinct values from a collection. Those data is in a field of a collection. It means I need to get set of name from the user collection.I tried it using cmd and I get the result as I need. But I can’t understand how to write the query in the spring file.Since I’m new to java I have not enough knowledge how to handle this.

Given below is a image of the database collection enter image description here

Services.java

JavaScript

I need to add this query inside

JavaScript

Advertisement

Answer

You can introduce a method in the UserRepository to retrieve the distinct firstName field values and return a List<String>.

JavaScript

The call to get the list of distinct first names:

JavaScript

This worked fine using Spring Data MongoDB v2.4 and MongoDB v4.2.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement