Search code examples
javaspringmongodbspring-mongo

Distinct Query in Mongo using Java Mao Access Pattern


I want to run a distinct query in mongo db using the spring framework java API. The query is something like this :

db.location.distinct("state");

How do I create the Query object for the above. Below is a bad try.

import org.springframework.data.mongodb.core.query.Query;

public List<Location> getLocations(int skipCount, int pageSize) 
{
        Query query = new Query(Criteria.where("state").is("distinct);
        return mongoOperations.find(query, Location.class);
        /*
         Don't want to do the below, as using Mao Pattern  --
         DBCollection collection = db.getCollection("location");
         DBObject o1 = new BasicDBObject();
         List list = collection.distinct("state", o1);
         return list;
       */
}

Solution

  • There actually is not a .distinct() method directly on MongoOperations, nor anything that really translates to one, save the aggregation framework.

    But you can just grab the method from the underlying Collection object directly:

    List states = mongoOperations.getCollection("location").distinct("state");
    

    Where of course to need to supply the collection name, as the Collection object from .getCollection() comes from the underlying Java driver.

    Or if you prefer, you can run the "command" form directly, but you still need to name the collection:

     BasicDBObject distinctCommand = new BasicDBObject("distinct", "location")
                .append("key", "state");
     List states = (List)mongoOperation.executeCommand(distinctCommand).get("values");