List of usage examples for com.mongodb DBCursor sort
public DBCursor sort(final DBObject orderBy)
From source file:com.caci.dummyserver.MongoRepository.java
public GetObjectsResult getObjects(String table, Collection<Pair<String, String>> keys, Collection<String> fields, Collection<Pair<String, Collection<String>>> filters, Collection<String> sort, Integer offset, Integer limit) { DB db = mongo.getDB("Objects"); DBCollection col = db.getCollection(table); GetObjectsResult result = new GetObjectsResult(); DBObject queryObject = makeQueryObject(keys, filters); DBCursor cursor = col.find(queryObject); try {/* ww w . j a v a2 s . com*/ if (sort != null && !sort.isEmpty()) { DBObject sortObj = new BasicDBObject(); for (String fieldName : sort) { if (fieldName.startsWith("-")) { sortObj.put("data." + fieldName.substring(1), -1); } else { sortObj.put("data." + fieldName, 1); } } cursor.sort(sortObj); } result.setTotal(cursor.count()); if (offset != null && offset > 0) { cursor.skip(offset); } if (limit != null && limit > 0) { cursor.limit(limit); } while (cursor.hasNext()) { DBObject obj = cursor.next(); obj = pruneDBObject(getData(obj), fields); result.getResults().add(obj.toString()); } } finally { cursor.close(); } return result; }
From source file:com.cyslab.craftvm.rest.mongo.QueryServlet.java
License:GNU General Public License
@Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.trace("doPost()"); // server auth if (!can_read(req)) { res.sendError(SC_UNAUTHORIZED);// w w w . j av a2s.c om return; } String ret = null; 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: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;/*from w w w .j a v a 2s . 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 2s .c o m*/ 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//w w w.j av a2 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;//w ww .j a v a2 s. c o 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 w w. j a va 2 s .co m*/ 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);//from www . ja va 2 s . c om } 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 w w w . ja va 2s. co 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.example.labs.actions.data.ProjectsAction.java
License:Apache License
public String execute() throws Exception { connection = MongoDBConnection.getInstance(); connection.connect("turbines"); DBCollection turbineData = connection.getMongoCollection("turbineData"); DBObject searchQuery = new BasicDBObject(); searchQuery.put("date", BasicDBObjectBuilder.start("$gte", startDate).add("$lte", endDate).get()); DBObject keys = new BasicDBObject(); keys.put("date", "1"); //from query param if (StringUtils.isEmpty(fields)) { success = 0;/*from w ww . j av a 2s. c o m*/ error = "Please provide valid fields"; return ERROR; } String[] fieldKeys = fields.split(","); for (String k : fieldKeys) { keys.put(k, "1"); } DBCursor cursor = turbineData.find(searchQuery, keys); DBObject sortTime = new BasicDBObject(); sortTime.put("date", 1); cursor.sort(sortTime); List<DBObject> dataPoints = cursor.toArray(); LOG.debug("Number of data points: " + dataPoints.size()); data = new ArrayList<Object>(); for (DBObject dataP : dataPoints) { data.add(dataP); } success = 1; return SUCCESS; }