tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 No SQL > Mongo DB > How to get distinct values for a given key

How to get distinct values for a given key 

MongoDB is a scalable, high-performance, open source NoSQL database. It offers Ad hoc queries, Indexing, Replication, Load balancing, File storage (GridFS), Aggregation, MapReduce and Server-side JavaScript execution. This requires the library mongo-2.8.0.jar to be present in the classpath. The following example shows how to get distinct values of a field.

File Name  :  mycountries.json

File Name  :  
com/bethecoder/tutorials/mongodb/tests/GetDistinctTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.mongodb.tests;

import java.net.UnknownHostException;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class GetDistinctTest {

  /**
   @param args
   */
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {

    try {
      //Connect to mongoDB with given IP and PORT
      Mongo mongo = new Mongo("localhost"27017);
      
      //Get the database object
      DB database = mongo.getDB("mytestdb");
      
      //Gets a collection with a given name.
      DBCollection countries = database.getCollection("mycountries");
      
      //Get distinct values for this key
      List countryNames = countries.distinct("country");
      System.out.println(countryNames);
      
      List stateNames = countries.distinct("state");
      System.out.println(stateNames);
      
    catch (UnknownHostException e) {
      e.printStackTrace();
    catch (MongoException e) {
      e.printStackTrace();
    }
  }
}
   

It gives the following output,
[ "India" , "USA" , "China"]
[ "Andhra Pradesh" , "Karnataka" , "Florida" , "Beijing" , "Yumen"]



 
  


  
bl  br