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.

MongoDB distinct

MongoDB distinct Query
The syntax for MongoDB distinct method is

db.collection.distinct(field, query)

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.

>'speed')[ 65, 55, 52, 45 ]

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.

>'name',{speed:{$gt:50}})[ "WagonR", "Xylo", "Alto800", "Astar", "Suzuki S-4", "Santro-Xing", "Palio", "Micra"]>

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.

package com.journaldev.mongodb;import;import java.util.List;import com.mongodb.BasicDBObject;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBObject;import com.mongodb.MongoClient;public class MongoDBDistinct { public static void distinct() throws UnknownHostException{ //Get a new connection to the db assuming that it is running MongoClient m1 = new MongoClient(); //use test as a database,use your database here DB db = m1.getDB("journaldev"); //fetch the collection object ,car is used here,use your own DBCollection coll = db.getCollection("car"); //call distinct method and store the result in list l1 List cl1= coll.distinct("speed"); //iterate through the list and print the elements for(int i=0;i<cl1.size();i++){ System.out.println(cl1.get(i)); } } public static void distinctquery() throws UnknownHostException{ MongoClient m1 = new MongoClient(); DB db = m1.getDB("journaldev"); DBCollection coll = db.getCollection("car"); //condition to fetch the car document whose speed is greater than 50 DBObject o1 = new BasicDBObject("speed",new BasicDBObject("$gt",50)); //call distinct method by passing the field name and object o1 List l1= coll.distinct("name", o1); System.out.println("-----------------------"); for(int i=0;i<l1.size();i++){ System.out.println(l1.get(i)); } } public static void main(String[] args) throws UnknownHostException{ //invoke all the methods to perform distinct operation distinct(); distinctquery(); }}

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.

  • 56