Example usage for com.mongodb DBCursor sort

List of usage examples for com.mongodb DBCursor sort

Introduction

In this page you can find the example usage for com.mongodb DBCursor sort.

Prototype

public DBCursor sort(final DBObject orderBy) 

Source Link

Document

Sorts this cursor's elements.

Usage

From source file:mongodb.findPagging.java

public static void pageResults(DBCollection collection, Integer skip) {
    BasicDBObject query = new BasicDBObject("first", "w");
    DBCursor cursor = collection.find(query);
    cursor.sort(new BasicDBObject("word", 1));
    cursor.limit(10);//from w  w  w  .  j  a v  a2s .  c o m
    cursor.skip(skip);
    System.out.println("Page " + new Integer(skip + 1).toString() + " to "
            + new Integer(skip + cursor.size()).toString() + ":");
    findPagging.displayCursor(cursor);
    if (cursor.size() == 10) {
        findPagging.pageResults(collection, skip + 10);
    }
}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewTopKResources(int requesterID, int profileOwnerID, int k,
        Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (profileOwnerID < 0 || requesterID < 0 || k < 0)
        return -1;

    com.mongodb.DB db = null;//from   w ww  .  java  2  s  . com

    try {
        db = mongo.getDB(database);
        db.requestStart();
        if (scanResources) {
            DBCollection collection = db.getCollection("resources");
            // find all resources that belong to profileOwnerID
            // sort them by _id desc coz we want latest ones and get the top
            // k
            DBObject q = new BasicDBObject().append("walluserid", Integer.toString(profileOwnerID));
            DBCursor queryResult = null;
            queryResult = collection.find(q);
            // DBObject s = new BasicDBObject().append("_id", -1); //desc
            DBObject s = new BasicDBObject(); // desc
            s.put("_id", -1);
            queryResult = queryResult.sort(s);
            queryResult = queryResult.limit(k);
            Iterator it = queryResult.iterator();
            while (it.hasNext()) {
                HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                DBObject oneRes = new BasicDBObject();
                oneRes.putAll((DBObject) it.next());
                vals.putAll(oneRes.toMap());
                // needed to do this so the coreworkload will not need to
                // know the datastore type
                if (vals.get("_id") != null) {
                    String tmp = vals.get("_id") + "";
                    vals.remove("_id");
                    vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
                }
                if (vals.get("walluserid") != null) {
                    String tmp = vals.get("walluserid") + "";
                    vals.remove("walluserid");
                    vals.put("walluserid", new ObjectByteIterator(tmp.getBytes()));
                }
                if (vals.get("creatorid") != null) {
                    String tmp = vals.get("creatorid") + "";
                    vals.remove("creatorid");
                    vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
                }
                result.add(vals);
            }
            queryResult.close();

        } else {
            DBCollection collection = db.getCollection("users");
            DBObject q = new BasicDBObject().append("_id", profileOwnerID);
            DBObject queryResult = null;
            queryResult = collection.findOne(q);
            String x = queryResult.get("wallResources").toString();
            if (!x.equals("[ ]")) {
                x = x.substring(1, x.length() - 1);
                String resourceIds[] = x.split(",");
                BasicDBObject query = new BasicDBObject();
                List<Integer> list = new ArrayList<Integer>();
                for (int i = resourceIds.length - 1; i >= resourceIds.length
                        - Math.min(k, resourceIds.length); i--) { // to
                    // limit
                    // it
                    list.add(Integer.parseInt(resourceIds[i].trim()));
                }
                collection = db.getCollection("resources");
                query.put("_id", new BasicDBObject("$in", list));
                DBCursor cursor = collection.find(query);
                while (cursor.hasNext()) {
                    HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                    vals.putAll(cursor.next().toMap());
                    if (vals.get("_id") != null) {
                        String tmp = vals.get("_id") + "";
                        vals.remove("_id");
                        vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    if (vals.get("walluserid") != null) {
                        String tmp = vals.get("walluserid") + "";
                        vals.remove("walluserid");
                        vals.put("walluserid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    if (vals.get("creatorid") != null) {
                        String tmp = vals.get("creatorid") + "";
                        vals.remove("creatorid");
                        vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
                    }
                    result.add(vals);
                }
                cursor.close();
            }
        }
    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;

}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

public int getCreatedResources(int creatorID, Vector<HashMap<String, ByteIterator>> result) {
    int retVal = 0;
    if (creatorID < 0)
        return -1;

    com.mongodb.DB db = null;/* w  ww  .  j  a  va 2s . c o  m*/

    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("resources");
        // find all resources that belong to profileOwnerID
        // sort them by _id desc coz we want latest ones and get the top k
        DBObject q = new BasicDBObject().append("creatorid", Integer.toString(creatorID));
        DBCursor queryResult = null;
        queryResult = collection.find(q);
        // DBObject s = new BasicDBObject().append("_id", -1); //desc
        DBObject s = new BasicDBObject(); // desc
        s.put("_id", -1);
        queryResult = queryResult.sort(s);
        Iterator it = queryResult.iterator();
        while (it.hasNext()) {
            HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
            DBObject oneRes = new BasicDBObject();
            oneRes.putAll((DBObject) it.next());
            vals.putAll(oneRes.toMap());
            // needed to do this so the coreworkload will not need to know
            // the datastore typr
            if (vals.get("_id") != null) {
                String tmp = vals.get("_id") + "";
                vals.remove("_id");
                vals.put("rid", new ObjectByteIterator(tmp.getBytes()));
            }
            if (vals.get("creatorid") != null) {
                String tmp = vals.get("creatorid") + "";
                vals.remove("creatorid");
                vals.put("creatorid", new ObjectByteIterator(tmp.getBytes()));
            }
            result.add(vals);
        }
        queryResult.close();

    } catch (Exception e) {
        System.out.println(e.toString());
        retVal = -1;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
    return retVal;

}

From source file:mongodb.sortDocument.java

public static void sortWordsAscending(DBCollection collection) {
    BasicDBObject query = new BasicDBObject("first", "w");
    DBCursor cursor = collection.find(query);
    BasicDBObject sorter = new BasicDBObject("word", 1);
    cursor.sort(sorter);
    System.out.println("\nW words ordered ascending: ");
    sortDocument.displayCursor(cursor);/*w w w  . jav a  2s.co  m*/
}

From source file:mongodb.sortDocument.java

public static void sortWordsDesc(DBCollection collection) {
    BasicDBObject query = new BasicDBObject("first", "w");
    DBCursor cursor = collection.find(query);
    BasicDBObject sorter = new BasicDBObject("word", -1);
    cursor.sort(sorter);
    System.out.println("\nW words ordered descending: ");
    sortDocument.displayCursor(cursor);//from www  . jav a 2s .  c om
}

From source file:mongodb.sortDocument.java

public static void sortWordsAscAndSize(DBCollection collection) {
    BasicDBObject query = new BasicDBObject("first", "q");
    DBCursor cursor = collection.find(query);
    BasicDBObject sorter = new BasicDBObject("last", 1);
    sorter.append("size", -1);
    cursor.sort(sorter);
    System.out.println("\nQ words ordered first by last letter " + "and then by size: ");
    sortDocument.displayCursor(cursor);//from   w w  w. j  a  va 2s.c  o  m
}

From source file:mx.edu.cide.justiciacotidiana.v1.mongo.MongoInterface.java

License:Open Source License

/**
 * Obtiene la lista de los elementos de una coleccin en formato JSON. Si se proporciona una referencia, se hace un filtrado.
 * @param collectionName Nombre de la coleccin de donde se extraern los elementos.
 * @param query Objeto de referencia para la bsqueda.
 * @return Cadena JSON con el resultado.
 *///from  ww w. j  a va 2  s  .c o m
public String listItemsAsJSON(String collectionName, BasicDBObject query) {
    DBCursor cursor = findItems(collectionName, query);
    cursor.sort(new BasicDBObject(FIELD_CREATED, -1));
    StringBuilder ret = new StringBuilder();
    long count = 0;

    if (null != cursor && cursor.hasNext()) {
        count = cursor.size();
    }
    ret.append("{\"count\":").append(count);
    if (cursor.hasNext()) {
        ret.append(", \"items\": [");
        try {
            while (cursor.hasNext()) {
                BasicDBObject t = (BasicDBObject) cursor.next();
                ret.append(Utils.JSON.toJSON(t));
                if (cursor.hasNext())
                    ret.append(",");
            }
        } finally {
            cursor.close();
        }
        ret.append("]");
    }
    ret.append("}");
    return ret.toString();
}

From source file:mx.edu.cide.justiciacotidiana.v1.services.Propuestas.java

License:Open Source License

private String getProposalsJSON(String categoryId) {
    StringBuilder ret = new StringBuilder();
    BasicDBObject query = null;//from   ww w .jav a 2  s. c o m
    if (null != categoryId && categoryId.length() > 0) {
        query = new BasicDBObject(Propuesta.FIELDS.CATEGORYID, categoryId);
    }

    long count = 0;
    DBCursor propuestas = Utils.mongo.findItems(MongoInterface.COLLECTIONS.PROPUESTAS, query);
    propuestas.sort(new BasicDBObject(Propuesta.FIELDS.CREATED, -1));

    if (null != propuestas && propuestas.hasNext()) {
        count = propuestas.size();
    }

    ret.append("{\"count\":").append(count);

    if (count > 0) {
        ret.append(", \"items\": [");
        try {
            while (propuestas.hasNext()) {
                BasicDBObject propuesta = (BasicDBObject) propuestas.next();
                ObjectId pId = (ObjectId) propuesta.get(Propuesta.FIELDS.MONGOID);
                String key = pId.toString();
                BasicDBList comments = getCommentsList(key);
                BasicDBList likes = getLikes(key);
                BasicDBList dislikes = getDisLikes(key);
                BasicDBList refrains = getRefrains(key);

                BasicDBObject commentsContainer = new BasicDBObject("data", comments);
                propuesta.put(Propuesta.FIELDS.COMMENTS, commentsContainer);

                BasicDBObject votes = new BasicDBObject();

                //Muy verbose y con muchos niveles, se puede simplificar la estructura
                BasicDBObject _likes = new BasicDBObject(Voto.PARTICIPANTS, likes);
                votes.put(Voto.LIKE, _likes);

                //Muy verbose y con muchos niveles, se puede simplificar la estructura
                BasicDBObject _dislikes = new BasicDBObject(Voto.PARTICIPANTS, dislikes);
                votes.put(Voto.DISLIKE, _dislikes);

                //Muy verbose y con muchos niveles, se puede simplificar la estructura
                BasicDBObject _refrains = new BasicDBObject(Voto.PARTICIPANTS, refrains);
                votes.put(Voto.REFRAIN, _refrains);

                propuesta.append(Propuesta.FIELDS.VOTES, votes);

                ret.append(Utils.JSON.toJSON(propuesta));
                if (propuestas.hasNext())
                    ret.append(",");
            }
        } catch (MongoException ex) {
            System.out.println("Error al genera lista de comentarios asociada a propuesta");
        }
        ret.append("]");
    }
    ret.append("}");
    return ret.toString();
}

From source file:net.ion.framework.db.mongo.jdbc.Executor.java

License:Apache License

DBCursor query() throws MongoSQLException {
    if (!(stmt instanceof Select))
        throw new IllegalArgumentException("not a query sql statement");

    Select select = (Select) stmt;/*from   w  ww  .  j a  v a 2s . c o m*/
    if (!(select.getSelectBody() instanceof PlainSelect))
        throw new UnsupportedOperationException("can only handle PlainSelect so far");

    PlainSelect ps = (PlainSelect) select.getSelectBody();
    if (!(ps.getFromItem() instanceof Table))
        throw new UnsupportedOperationException("can only handle regular tables");

    DBCollection coll = getCollection((Table) ps.getFromItem());

    BasicDBObject fields = new BasicDBObject();
    for (Object o : ps.getSelectItems()) {
        SelectItem si = (SelectItem) o;
        if (si instanceof AllColumns) {
            if (fields.size() > 0)
                throw new UnsupportedOperationException("can't have * and fields");
            break;
        } else if (si instanceof SelectExpressionItem) {
            SelectExpressionItem sei = (SelectExpressionItem) si;
            fields.put(toFieldName(sei.getExpression()), 1);
        } else {
            throw new UnsupportedOperationException("unknown select item: " + si.getClass());
        }
    }

    // where
    DBObject query = parseWhere(ps.getWhere());

    // done with basics, build DBCursor
    DBCursor cur = coll.find(query, fields);

    { // order by
        List orderBylist = ps.getOrderByElements();
        if (orderBylist != null && orderBylist.size() > 0) {
            BasicDBObject order = new BasicDBObject();
            for (int i = 0; i < orderBylist.size(); i++) {
                OrderByElement o = (OrderByElement) orderBylist.get(i);
                order.put(o.getColumnReference().toString(), o.isAsc() ? 1 : -1);
            }
            cur.sort(order);
        }
    }

    return cur;
}

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

License:GNU General Public License

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

    log.fine("doPost()");

    // server auth
    String ret;/*from w ww  .j  a  v  a 2s  .c  o m*/

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    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;
        }
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    String _fields = req.getParameter("fields");
    String fields[] = null;
    if (_fields != null)
        fields = _fields.split("[,]");

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

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

    BufferedReader r = null;
    DBObject q = null, sort = 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);
            if (cache != null) {
                buf.append(db_name);
                buf.append(col_name);
                buf.append(data);
            }
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }
        // sort param
        data = r.readLine();
        if (data != null) {
            try {
                sort = (DBObject) JSON.parse(data);
            } catch (JSONParseException e) {
                error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg"));
                return;
            }
            if (cache != null)
                buf.append(data);
        }

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

    // limit
    int lim;
    if (limit != null) {
        try {
            lim = Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN);
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            return;
        }
    } else {
        lim = MAX_FIELDS_TO_RETURN;
    }
    if (cache != null) {
        buf.append(";limit=");
        buf.append(lim);
    }

    // skip
    int sk = -1;
    if (skip != null) {
        try {
            sk = Integer.parseInt(skip);
            if (cache != null) {
                buf.append(";skip=");
                buf.append(sk);
            }
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            return;
        }
    }

    // fields
    if (cache != null && _fields != null) {
        buf.append(";fields=");
        buf.append(_fields);
    }

    // from cache
    String cache_key = null;
    if (cache != null) {
        cache_key = buf.toString();
        try {
            ret = (String) cache.get(cache_key);
        }
        // some wrong char in key
        catch (IllegalArgumentException e) {
            int l = buf.length();
            for (int i = 0; i < l; i++) {
                if (buf.charAt(i) == ' ')
                    buf.setCharAt(i, '*');
            }
            cache_key = buf.toString();
            ret = (String) cache.get(cache_key);
        }
        if (ret != null) {
            out_str(req, ret, "application/json");
            return;
        }
    }

    // cursor
    DBCursor c;
    if (fields != null) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        int len = fields.length;
        for (int i = 0; i < len; i++) {
            String s = fields[i];
            sb.append('"');
            sb.append(s);
            sb.append('"');
            sb.append(":1");
            if (i != (len - 1))
                sb.append(",");
        }
        sb.append("}");
        c = col.find(q, (DBObject) JSON.parse(sb.toString()));
    } else
        c = col.find(q);

    if (c == null || c.count() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    if (sort != null)
        c.sort(sort);

    res.setIntHeader("X-Documents-Count", c.count());

    c.limit(lim);
    if (sk != -1)
        c.skip(sk);

    // reset buf
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        if (rm_id)
            o.removeField("_id");
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }
    c.close();

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    ret = buf.toString();
    if (cache != null)
        cache.set(cache_key, ret);

    out_str(req, ret, "application/json");

}