List of usage examples for com.mongodb DBCursor skip
public DBCursor skip(final int numberOfElements)
From source file:io.liveoak.mongo.MongoCollectionResource.java
License:Open Source License
@Override public Collection<Resource> members(RequestContext ctx) throws Exception { LinkedList<Resource> members = new LinkedList<>(); DBObject returnFields = new BasicDBObject(); if (ctx.returnFields() != null && !ctx.returnFields().child(LiveOak.MEMBERS).isEmpty()) { ReturnFields membersReturnFields = ctx.returnFields().child(LiveOak.MEMBERS); if (!membersReturnFields.isAll()) { membersReturnFields.forEach((fieldName) -> { returnFields.put(fieldName, true); });/*ww w.j av a 2 s.c o m*/ } } DBCursor dbCursor = dbCollection.find(queryObject, returnFields); ResourceParams resourceParams = ctx.resourceParams(); if (resourceParams != null && resourceParams.contains("hint")) { String hint = resourceParams.value("hint"); if (hint.startsWith("{")) { try { DBObject hintObject = (DBObject) JSON.parse(hint); dbCursor.hint(hintObject); } catch (Exception e) { throw new NotAcceptableException(uri().toString(), "Invalid JSON format for the 'hint' parameter", e); } } else { dbCursor.hint(hint); } } if (explainQuery) { members.add(new MongoEmbeddedObjectResource(this, dbCursor.explain())); } else { Sorting sorting = ctx.sorting(); if (sorting != null) { BasicDBObject sortingObject = new BasicDBObject(); for (Sorting.Spec spec : sorting) { sortingObject.append(spec.name(), spec.ascending() ? 1 : -1); } dbCursor = dbCursor.sort(sortingObject); } Pagination pagination = ctx.pagination(); if (pagination != null) { dbCursor.limit(pagination.limit()); dbCursor.skip(pagination.offset()); } try { dbCursor.hasNext(); } catch (Exception e) { throw new ResourceProcessingException( "Exception encountered trying to fetch data from the Mongo Database", e); } dbCursor.forEach((dbObject) -> { members.add(new MongoBaseObjectResource(this, dbObject)); }); } return members; }
From source file:jahspotify.storage.statistics.MongoDBHistoricalStorage.java
License:Apache License
@Override public Collection<TrackHistory> getHistory(final int index, final int count, final HistoryCriteria... historyCriterias) { final DBCollection tracks = _db.getCollection("history"); final DBCursor dbObjects = tracks.find(); dbObjects.skip(index); dbObjects.limit(count);//from ww w . j a v a2s .c o m final BasicDBObject orderBy = new BasicDBObject(); orderBy.put("startTime", -1); dbObjects.sort(orderBy); return new AbstractCollection<TrackHistory>() { @Override public Iterator<TrackHistory> iterator() { return new MongoDBHistoryCursor(dbObjects); } @Override public int size() { return dbObjects.size(); } }; }
From source file:me.carbou.mathieu.tictactoe.db.DBCollection.java
License:Apache License
public Stream<Map<String, Object>> find(Map where, Map fields, Map sort, Function<Map, Map> transform, int limit, int skip) { final DBCursor cursor = getCollection().find(new BasicDBObject(addWhere(where)), new BasicDBObject(preFind(fields))); if (!sort.isEmpty()) cursor.sort(new BasicDBObject(sort)); if (skip > 0) cursor.skip(skip); if (limit > DB.NO_LIMIT) cursor.limit(limit);/* w w w . j a va 2s .c o m*/ int est = cursor.size(); Spliterator<Map<String, Object>> spliterator = new Spliterators.AbstractSpliterator<Map<String, Object>>( est, NONNULL | ORDERED | SIZED | IMMUTABLE) { @Override public boolean tryAdvance(Consumer<? super Map<String, Object>> action) { if (cursor.hasNext()) { action.accept(postFind(where, cursor.next(), transform)); return true; } else { cursor.close(); return false; } } }; return StreamSupport.stream(spliterator, false); }
From source file:me.yyam.mongodbutils.MongoDbOperater.java
public List find(QueryInfo queryInfo) { DB db = mongoClient.getDB(queryInfo.dbName); DBCollection coll = db.getCollection(queryInfo.collName); DBCursor cursor = null; if (queryInfo.query != null) { cursor = coll.find(queryInfo.query); } else {//from w ww . j a v a 2 s . co m cursor = coll.find(); } if (queryInfo.order != null) { cursor = cursor.sort(queryInfo.order); } if (queryInfo.limit != null) { cursor.limit(queryInfo.limit.intValue()); } if (queryInfo.skip != null) { cursor.skip(queryInfo.skip.intValue()); } return cursor2list(cursor); }
From source file:me.yyam.mongodbutils.MongoDbOperater.java
public List<Map> find(DBCollection coll, DBObject query, DBObject order, int start, int limit) { DBCursor cursor = null; if (query == null) { cursor = coll.find();//w w w . j a v a 2 s . co m } else { cursor = coll.find(query); } if (order != null) cursor = cursor.sort(order); if (start != 0 && limit != 0) { cursor.skip(start).limit(limit); } if (start == 0 && limit != 0) { cursor.limit(limit); } return cursor2list(cursor); }
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 ww w . j av a 2 s . 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:net.kamradtfamily.mongorest.AggregateServlet.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"); if (db_name == null || col_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return;/*w w w .j a v a 2 s . co m*/ } String skip = req.getParameter("skip"); String limit = req.getParameter("limit"); DB db = mongo.getDB(db_name); DBCollection col = db.getCollection(col_name); 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); } 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; } } } finally { if (r != null) r.close(); } DBCursor c; if (sort == null) c = col.find(q); else c = col.find(q).sort(sort); if (c == null) { 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(); // reset buf buf.setLength(0); int no = 0; buf.append("["); while (c.hasNext()) { DBObject o = c.next(); JSON.serialize(o, buf); buf.append(","); no++; } 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:net.kamradtfamily.mongorest.AggregateServlet.java
License:GNU General Public License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doGet()"); String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); if (db_name == null || col_name == null) { error(res, SC_BAD_REQUEST, Status.get("param name missing")); return;/* w w w . j a v a 2s. com*/ } String skip = req.getParameter("skip"); String limit = req.getParameter("limit"); DB db = mongo.getDB(db_name); DBCollection col = db.getCollection(col_name); DBCursor c = col.find(); if (c == null) { 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(); JSON.serialize(o, buf); buf.append(","); no++; } 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: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 w w . ja v a2s . co 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"); }
From source file:net.kamradtfamily.mongorest.QueryServlet.java
License:GNU General Public License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.fine("doGet()"); 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];//from www.j a v a 2s. c om 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"); }