MongoDB distinct Query With Examples

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.

MongoDB distinct

The syntax for MongoDB distinct method is

field: A string type for which the discrete values are to be returned.

query: Specifies the document from which discrete values are to be retrieved.

Let’s see into the examples of select distinct values using mongo shell.

Above mongo distinct example selects an array of distinct values for speed field in the car collection. Notice that query parameter is optional. Now let’s look at the example where we will pass distinct query parameter to select distinct values that matches the query criteria.

Above MongoDB distinct query operation find the names of the car whose speed is greater than 50 in the car collection.

MongoDB distinct Java Program

Consider the following java program to perform distinct operation on the car collection which prints a set of discrete values for the fields specified by the user.

Output of the above MongoDB distinct java program is:

That’s all for MongoDB distinct examples. This is very helpful when you want to select distinct fields from a collection based on a certain criteria.

By admin

Leave a Reply

%d bloggers like this: