Example usage for com.mongodb DBCollection distinct

List of usage examples for com.mongodb DBCollection distinct

Introduction

In this page you can find the example usage for com.mongodb DBCollection distinct.

Prototype

@SuppressWarnings("unchecked")
public List distinct(final String fieldName, final DBCollectionDistinctOptions options) 

Source Link

Document

Find the distinct values for a specified field across a collection and returns the results in an array.

Usage

From source file:com.andreig.jetty.DistinctServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doPost()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);//w  ww.j a  v  a 2 s . c  o m
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    String key = req.getParameter("key");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    if (key == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }

    List<?> l = col.distinct(key, q);
    if (l == null || l.size() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", l.size());

    StringBuilder buf = tl.get();
    // reset buf
    buf.setLength(0);

    JSON.serialize(l, buf);
    out_str(req, buf.toString(), "application/json");

}

From source file:com.cyslab.craftvm.rest.mongo.DistinctServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPost()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from   w w  w  .  j  av  a2  s  . c  o  m*/
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    String key = req.getParameter("key");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    if (key == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }

    List l = col.distinct(key, q);
    if (l == null || l.size() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", l.size());

    StringBuilder buf = tl.get();
    // reset buf
    buf.setLength(0);

    JSON.serialize(l, buf);
    out_str(req, buf.toString(), "application/json");

}

From source file:com.joyfulmongo.db.javadriver.JFDBQuery.java

License:Apache License

public List<String> distinct() {
    DBCollection collection = getDBCollection(collectionName);
    List<String> result = collection.distinct(this.distinctField, this.constraints);
    return result;
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

/**
 * {@inheritDoc}/*from   www.j  a  va 2s  .c  o  m*/
 */
@Override
public <T extends Model> List<String> distinct(Class<T> clazz, String f, Filter filter) {

    DBObject query = this.getCachedFilter(filter);
    DBCollection dbCollection = this.getCollection(clazz);
    f = this.filterSerializer.mapFieldToProperty(f, new Object());
    return dbCollection.distinct(f, query);

}

From source file:fr.cnes.sitools.datasource.mongodb.business.SitoolsMongoDBDataSource.java

License:Open Source License

/**
 * Make the SQL request//ww  w  .  jav  a  2s  . c  om
 * 
 * @param key
 *          the key
 * @param request
 *          the mongoBD request model
 * @return List of Object
 * 
 * 
 */
@SuppressWarnings("unchecked")
public List<Object> distinctQuery(String key, MongoDBRequestModel request) {
    List<Object> results = null;
    try {
        DBObject dbObjectQuery = (DBObject) JSON.parse(request.getFilterString());
        DB database = getDatabase();
        DBCollection collection = database.getCollection(request.getCollectionName());

        results = collection.distinct(key, dbObjectQuery);
        return results;
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:mongodb.JavaFindDistinct.java

public static void sizesOfQWords(DBCollection collection) {
    BasicDBObject query = new BasicDBObject("first", "q");
    List<Double> results = collection.distinct("size", query);
    System.out.println("\nDistinct Sizes of words starting with Q: ");
    System.out.println(results.toString());
}

From source file:mongodb.JavaFindDistinct.java

public static void firstLetterOfLongWords(DBCollection collection) {
    BasicDBObject query = new BasicDBObject("size", new BasicDBObject("$gt", 12));
    List<String> results = collection.distinct("first", query);
    System.out.println("\nDistinct first letters of words longer " + "than  12 characters: ");
    System.out.println(results.toString());
}

From source file:mongodb.Ratings_5.java

public static void main(String[] args) throws UnknownHostException {
    MongoClient mongo = new MongoClient();
    DB db = mongo.getDB("db");
    DBCollection Collection = db.getCollection("ratings");

    //Specifying Rating = 5 in BasicDBObject since we want to find out movie id's for which Rating = 3
    BasicDBObject object = new BasicDBObject("Rating", 3);

    //Creating List to find out distinct movie ids which have rating = 3
    List MovieId = Collection.distinct("MovieID", object);

    System.out.println("The Movie Id's with rating 3: \n");

    for (int i = 0; i < MovieId.size(); i++) {
        System.out.println(MovieId.get(i).toString());
    }//from   w w  w.  jav  a  2s .  c om

}

From source file:net.kamradtfamily.mongorest.DistinctServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doPost()");

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    String key = req.getParameter("key");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];/*from  w w  w  . jav a2s  . c o  m*/
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    if (key == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }

    List l = col.distinct(key, q);
    if (l == null || l.isEmpty()) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", l.size());

    StringBuilder buf = tl.get();
    // reset buf
    buf.setLength(0);

    JSON.serialize(l, buf);
    out_str(req, buf.toString(), "application/json");

}

From source file:org.chililog.server.data.RepositoryEntryController.java

License:Apache License

/**
 * Count of number of entries that matches the condition
 * /*from  w  w  w  .  j av  a 2s  . co  m*/
 * @param db
 *            Database connection
 * @param criteria
 *            Criteria to filter resultset. Fields and Conditions is used.
 * @return List of distinct values for the nominated field.
 */
@SuppressWarnings("rawtypes")
public List executeDistinctQuery(DB db, RepositoryEntryListCriteria criteria) throws ChiliLogException {
    try {
        if (db == null) {
            throw new NullArgumentException("db");
        }
        if (criteria == null) {
            throw new NullArgumentException("criteria");
        }

        DBCollection coll = db.getCollection(this.getDBCollectionName());

        DBObject fields = criteria.getFieldsDbObject();
        if (fields == null || fields.keySet().isEmpty()) {
            throw new IllegalArgumentException("Field is required for a 'distinct' query.");
        }

        String fieldName = null;
        for (String n : fields.keySet()) {
            fieldName = n;
            break;
        }

        DBObject conditions = criteria.getConditionsDbObject();

        return coll.distinct(fieldName, conditions);
    } catch (Exception ex) {
        throw new ChiliLogException(ex, Strings.MONGODB_QUERY_ERROR, ex.getMessage());
    }
}