Example usage for com.mongodb DBCursor limit

List of usage examples for com.mongodb DBCursor limit

Introduction

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

Prototype

public DBCursor limit(final int limit) 

Source Link

Document

Limits the number of elements returned.

Usage

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

License:GNU General Public License

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

    log.trace("doGet()");

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

    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");

    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);

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

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

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

    if (skip != null) {
        try {
            c.skip(Integer.parseInt(skip));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            c.close();
            return;
        }
    }

    StringBuilder buf = tl.get();
    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);

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

}

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

License:GNU General Public License

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

    log.trace("doPost()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from  w  w w . j a va2  s.c  o  m*/
        return;
    }

    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;
        }
    }

    boolean upsert = Boolean.parseBoolean(req.getParameter("upsert"));
    boolean multi = Boolean.parseBoolean(req.getParameter("multi"));

    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);

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

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

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

        String fn = col.getFullName();
        DBCursor c = col.find(q);
        int cnt = c.count();
        if (!multi)
            c.limit(1);
        long l = multi ? cnt : 1;
        String toupdate[] = new String[(int) l];
        int n = 0;
        boolean insert = false;

        if (upsert && !multi && cnt == 0)
            insert = true;

        while (c.hasNext()) {

            DBObject _o = c.next();
            ObjectId oid = (ObjectId) _o.get("_id");
            String id = oid.toStringMongod();
            toupdate[n++] = id;

        }
        c.close();

        List<String> flds = Config.search_index_fields.get(fn);
        boolean commit = false;
        Document doc = null;
        Search _writer = search.get_writer();
        if (flds != null && flds.size() > 0) {
            doc = new Document();
            try {
                for (String fld : flds) {
                    String val = (String) o.get(fld);
                    if (val == null)
                        continue;
                    _writer.add_searchable_s(doc, fld, val);
                    commit = true;
                }
                if (commit)
                    _writer.commit(doc);
            } catch (ClassCastException e) {
                error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String"));
                return;
            } catch (CorruptIndexException e) {
                error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e));
                return;
            }
        }
        if (commit && insert)
            log.warn("upsert with search not implemented yet");
        else
            _writer.update(toupdate, doc);

    }

    WriteResult wr = col.update(q, o, upsert, multi, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_CREATED);

}

From source file:com.ebay.cloud.cms.dal.persistence.MongoExecutor.java

License:Apache License

public static List<DBObject> find(PersistenceContext context, MetaClass metadata, DBObject queryObject,
        DBObject fieldObject, SearchOption option) {
    long start = System.currentTimeMillis();
    String msg = "success";
    DBCollection dbCollection = context.getDBCollection(metadata);
    DBCursor findCursor = null;
    Integer size = 0;/*  w ww.j  a v  a 2  s.  c om*/
    try {
        findCursor = dbCollection.find(queryObject, fieldObject);
        // set option
        if (option.hasLimit()) {
            findCursor.limit(option.getLimit());
        }
        if (option.hasSkip()) {
            findCursor.skip(option.getSkip());
        }
        if (option.hasSort()) {
            findCursor.sort(option.getSort());
        }
        // populate search result
        List<DBObject> result = findCursor.toArray();
        size = result.size();
        return result;
    } catch (Throwable t) {
        msg = t.getMessage();
        handleMongoException(t);
    } finally {
        if (findCursor != null) {
            findCursor.close();
        }
        logMongoAction(context, "find", start, dbCollection, queryObject, fieldObject, option, size, msg);
    }
    return Collections.emptyList();
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

public void find(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final DBObject query = ((DocBuilderField) getBoundUnit(Item.findQuery)).getDBObject();
    final DBObject fields = ((DocBuilderField) getBoundUnit(Item.findFields)).getDBObject();
    final DBObject sort = ((DocBuilderField) getBoundUnit(Item.findSort)).getDBObject();
    final DBObject hint = ((DocBuilderField) getBoundUnit(Item.findHint)).getDBObject();
    final int skip = getIntFieldValue(Item.findSkip);
    final int limit = getIntFieldValue(Item.findLimit);
    final int batchSize = getIntFieldValue(Item.findBatchSize);
    final boolean explain = getBooleanFieldValue(Item.findExplain);
    final boolean export = getBooleanFieldValue(Item.findExport);

    if (export) {
        exportToFile(col, query, fields, sort, skip, limit, batchSize);
    } else {/*from   w w w.  ja  va 2  s .  c  om*/
        new DbJob() {
            @Override
            public Object doRun() {
                // this does not actually block, may not need dbjob
                DBCursor cur = col.find(query, fields, skip, batchSize);
                if (sort != null) {
                    cur.sort(sort);
                }
                if (limit > 0) {
                    cur.limit(limit);
                }
                if (hint != null) {
                    cur.hint(hint);
                }
                if (explain) {
                    return cur.explain();
                }

                // force cursor to start
                cur.hasNext();
                return cur;
            }

            @Override
            public String getNS() {
                return col.getFullName();
            }

            @Override
            public String getShortName() {
                return "Find";
            }

            @Override
            public DBObject getRoot(Object result) {
                if (result == null || !(result instanceof DBCursor)) {
                    return null;
                }
                DBCursor res = (DBCursor) result;
                BasicDBObject obj = new BasicDBObject("cursorId", res.getCursorId());
                obj.put("server", res.getServerAddress().toString());
                obj.put("query", res.getQuery());
                obj.put("fields", res.getKeysWanted());
                obj.put("options", res.getOptions());
                obj.put("readPreference", res.getReadPreference().toDBObject());
                obj.put("numSeen", res.numSeen());
                obj.put("numGetMores", res.numGetMores());
                // want skip, limit, batchsize
                return obj;
            }

            @Override
            public ButtonBase getButton() {
                return button;
            }
        }.addJob();

    }
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

static void doFind(final DBCollection col, final DBObject query, final DBObject fields, final DBObject sort,
        final int skip, final int limit, final int batchSize, final boolean explain, final DBObject hint,
        final int options) {
    new DbJob() {
        @Override/*from   w ww .  j av a  2 s.co  m*/
        public Object doRun() {
            // this does not actually block, may not need dbjob
            DBCursor cur = col.find(query, fields).skip(skip).batchSize(batchSize).addOption(options);
            if (sort != null) {
                cur.sort(sort);
            }
            if (limit > 0) {
                cur.limit(limit);
            }
            if (hint != null) {
                cur.hint(hint);
            }
            if (explain) {
                return cur.explain();
            }

            // force cursor to start
            cur.hasNext();
            return cur;
        }

        @Override
        public String getNS() {
            return col.getFullName();
        }

        @Override
        public String getShortName() {
            return "Find";
        }

        @Override
        public DBObject getRoot(Object result) {
            if (result == null || !(result instanceof DBCursor)) {
                return null;
            }
            DBCursor res = (DBCursor) result;
            BasicDBObject obj = new BasicDBObject("cursorId", res.getCursorId());
            obj.put("query", res.getQuery());
            obj.put("fields", res.getKeysWanted());
            obj.put("options", res.getOptions());
            obj.put("readPreference", res.getReadPreference().toDBObject());
            obj.put("numSeen", res.numSeen());
            obj.put("numGetMores", res.numGetMores());
            // want skip, limit, batchsize
            return obj;
        }
    }.addJob();
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

private void exportToFile(final DBCollection col, final DBObject query, final DBObject fields,
        final DBObject sort, final int skip, final int limit, final int batchSize) {
    ExportDialog dia = UMongo.instance.getGlobalStore().getExportDialog();
    if (!dia.show()) {
        return;//from  w  w  w . j  a  va 2 s. co m
    }
    final DocumentSerializer ds = dia.getDocumentSerializer();
    final boolean continueOnError = dia.getBooleanFieldValue(ExportDialog.Item.continueOnError);
    new DbJob() {
        @Override
        public Object doRun() throws Exception {
            try {
                try {
                    DBCursor cur = col.find(query, fields);
                    if (skip > 0) {
                        cur.skip(skip);
                    }
                    if (batchSize != 0) {
                        cur.batchSize(batchSize);
                    }
                    if (sort != null) {
                        cur.sort(sort);
                    }
                    if (limit > 0) {
                        cur.limit(limit);
                    }
                    while (cur.hasNext() && !stopped) {
                        ds.writeObject(cur.next());
                    }
                } catch (Exception e) {
                    if (continueOnError) {
                        getLogger().log(Level.WARNING, null, e);
                    } else {
                        throw e;
                    }
                }
            } finally {
                ds.close();
            }
            return null;
        }

        @Override
        public String getNS() {
            return col.getFullName();
        }

        @Override
        public String getShortName() {
            return "Export";
        }
    }.addJob();
}

From source file:com.effektif.mongo.MongoWorkflowStore.java

License:Apache License

public DBCursor createWorkflowDbCursor(WorkflowQuery query) {
    BasicDBObject dbQuery = createDbQuery(query);
    DBCursor dbCursor = workflowsCollection.find("find-workflows", dbQuery);
    if (query.getLimit() != null) {
        dbCursor.limit(query.getLimit());
    }/*from   w ww .  j  a va2  s  .com*/
    if (query.getOrderBy() != null) {
        dbCursor.sort(writeOrderBy(query.getOrderBy()));
    }
    return dbCursor;
}

From source file:com.effektif.mongo.Query.java

License:Apache License

public void applyCursorConfigs(DBCursor dbCursor) {
    if (skip != null || limit != null) {
        log.debug("Applying page to cursor: skip=" + skip + ", limit=" + limit);
        if (skip != null) {
            dbCursor.skip(skip);/* ww  w .j  ava2  s .c o m*/
        }
        if (limit != null) {
            dbCursor.limit(limit);
        }
    }
    if (orderBy != null) {
        log.debug("Applying sort to cursor: " + orderBy);
        dbCursor.sort(orderBy);
    }
}

From source file:com.eharmony.matching.seeking.executor.mongodb.MongoQueryExecutor.java

License:Apache License

private <T, R> DBCursor translate(Query<T, R> query) {
    mapClasses(query.getEntityClass());//from  www.  j  a  v a 2s .c  o  m
    final DBObject translated = queryTranslator.translate(query);
    if (log.isDebugEnabled()) {
        log.debug(translated);
    }
    final DBObject fields = queryTranslator.translateProjection(query);
    final DBCursor cursor = find(getCollection(query.getEntityClass()), translated, fields);
    cursor.sort(queryTranslator.translateOrder(query));
    if (query.getMaxResults() != null) {
        cursor.limit(query.getMaxResults());
    }
    return cursor;
}

From source file:com.google.api.ads.adwords.jaxws.extensions.report.model.persistence.mongodb.MongoEntityPersister.java

License:Open Source License

/**
 * @see com.google.api.ads.adwords.jaxws.extensions.report.model.persistence.EntityPersister
 *      #get(java.lang.Class, java.util.Map, int, int)
 *///from ww w. j av a2  s  .  c o m
@Override
public <T, V> List<T> get(Class<T> t, Map<String, V> keyValueList, int numToSkip, int limit) {
    DBCollection dbcollection = getDBCollection(t, true);

    BasicDBObject query = new BasicDBObject();
    if (keyValueList != null) {
        for (String key : keyValueList.keySet()) {
            query.put(key, keyValueList.get(key));
        }
    }
    DBCursor cur = dbcollection.find(query);

    if (limit > 0) {
        cur.limit(limit);
    }
    if (numToSkip > 0) {
        cur.skip(numToSkip);
    }

    List<T> list = new ArrayList<T>();
    while (cur.hasNext()) {
        DBObject dbObject = cur.next();
        list.add(gson.fromJson(com.mongodb.util.JSON.serialize(dbObject), t));
    }
    return list;
}