List of usage examples for com.mongodb DBCursor explain
@Deprecated
public DBObject explain()
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 {/* w w w. j a 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/*from w w w . ja va 2 s . c o 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.hangum.tadpole.mongodb.core.composite.result.MongodbResultComposite.java
License:Open Source License
/** * ? ? .// ww w. j ava 2 s.c om * * @param basicFields * @param basicWhere * @param basicSort */ private void find(BasicDBObject basicFields, DBObject basicWhere, BasicDBObject basicSort, int cntSkip, int cntLimit) throws Exception { if ((cntLimit - cntSkip) >= defaultMaxCount) { // " " + defaultMaxCount + " ? . Prefernece? ? ." // Search can not exceed the number 5. Set in Perference. throw new Exception(String.format(Messages.MongoDBTableEditor_0, "" + defaultMaxCount)); //$NON-NLS-2$ //$NON-NLS-1$ } DB mongoDB = MongoDBQuery.findDB(userDB); DBCollection dbCollection = MongoDBQuery.findCollection(userDB, collectionName); // ?? DBCursor dbCursor = null; try { if (cntSkip > 0 && cntLimit > 0) { dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort).skip(cntSkip).limit(cntLimit); } else if (cntSkip == 0 && cntLimit > 0) { dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort).limit(cntLimit); } else { dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort); } DBObject explainDBObject = dbCursor.explain(); sbConsoleExecuteMsg.append(JSONUtil.getPretty(explainDBObject.toString())).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleErrorMsg.append(JSONUtil.getPretty(mongoDB.getLastError().toString())).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ mongoDB.forceError(); mongoDB.resetError(); // if(logger.isDebugEnabled()) logger.debug(sbConsoleMsg); // ?? . refreshDBView(dbCursor, dbCursor.count()); } finally { if (dbCursor != null) dbCursor.close(); } }
From source file:com.hangum.tadpole.mongodb.core.editors.main.MongoDBTableEditor.java
License:Open Source License
/** * ? ? .//from w ww. j a va2s .c o m * * @param basicFields * @param basicWhere * @param basicSort */ private void find(BasicDBObject basicFields, DBObject basicWhere, BasicDBObject basicSort, int cntSkip, int cntLimit) throws Exception { if ((cntLimit - cntSkip) >= defaultMaxCount) { // " " + defaultMaxCount + " ? . Prefernece? ? ." // Search can not exceed the number 5. Set in Perference. throw new Exception(String.format(Messages.MongoDBTableEditor_0, "" + defaultMaxCount)); //$NON-NLS-2$ } mapColumns = new HashMap<Integer, String>(); sourceDataList = new ArrayList<HashMap<Integer, Object>>(); DB mongoDB = MongoConnectionManager.getInstance(userDB); DBCollection dbCollection = mongoDB.getCollection(tableName); // ?? DBCursor dbCursor = null; try { if (cntSkip > 0 && cntLimit > 0) { sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Fields]" + basicFields.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Where]" + basicWhere.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Sort] " + basicSort.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Skip]" + cntSkip).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Limit]" + cntLimit).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("############[query]#####################"); //$NON-NLS-1$ dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort).skip(cntSkip).limit(cntLimit); } else if (cntSkip == 0 && cntLimit > 0) { sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Fields]" + basicFields.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Where]" + basicWhere.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Sort] " + basicSort.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Limit]" + cntLimit).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort).limit(cntLimit); } else { sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Fields]" + basicFields.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Where]" + basicWhere.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[Sort] " + basicSort.toString()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("############[query]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ dbCursor = dbCollection.find(basicWhere, basicFields).sort(basicSort); } DBObject explainDBObject = dbCursor.explain(); sbConsoleMsg.append("############[result]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ sbConsoleMsg.append("[query explain]\r\n" + JSONUtil.getPretty(explainDBObject.toString())) //$NON-NLS-1$ .append("\r\n"); //$NON-NLS-1$ sbConsoleMsg.append("[error]\r\n" + JSONUtil.getPretty(mongoDB.getLastError().toString())) //$NON-NLS-1$ .append("\r\n"); //$NON-NLS-1$ sbConsoleMsg.append("############[result]#####################").append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ mongoDB.forceError(); mongoDB.resetError(); if (logger.isDebugEnabled()) logger.debug(sbConsoleMsg); // ?? . int totCnt = 0; listTrees = new ArrayList<MongodbTreeViewDTO>(); for (DBObject dbObject : dbCursor) { // ? ? if (mapColumns.size() == 0) mapColumns = MongoDBTableColumn.getTabelColumnView(dbObject); // append tree text columnInfo.get(key) MongodbTreeViewDTO treeDto = new MongodbTreeViewDTO(dbObject, "(" + totCnt + ") {..}", "", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ "Document"); //$NON-NLS-1$ parserTreeObject(dbObject, treeDto, dbObject); listTrees.add(treeDto); // append table text HashMap<Integer, Object> dataMap = new HashMap<Integer, Object>(); for (int i = 0; i < mapColumns.size(); i++) { Object keyVal = dbObject.get(mapColumns.get(i)); if (keyVal == null) dataMap.put(i, ""); //$NON-NLS-1$ else dataMap.put(i, keyVal.toString()); } // ?? ? ? id dataMap.put(MongoDBDefine.PRIMARY_ID_KEY, dbObject); sourceDataList.add(dataMap); // append row text totCnt++; } txtCnt = dbCursor.count() + "/" + totCnt + Messages.MongoDBTableEditor_69; //$NON-NLS-1$ } finally { if (dbCursor != null) dbCursor.close(); } }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
private JSONObject lookupEntireRecord(String collectionName, String guid, boolean explain) throws RecordNotFoundException, FailedDBOperationException { long startTime = System.currentTimeMillis(); db.requestStart();/*w w w .j a v a 2 s . co m*/ try { String primaryKey = mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey().getName(); db.requestEnsureConnection(); DBCollection collection = db.getCollection(collectionName); BasicDBObject query = new BasicDBObject(primaryKey, guid); DBCursor cursor = collection.find(query); if (explain) { System.out.println(cursor.explain().toString()); } if (cursor.hasNext()) { DBObject obj = cursor.next(); // arun: optimized for the common case of Map @SuppressWarnings("unchecked") JSONObject json = obj instanceof Map ? DiskMapRecords.recursiveCopyMap((Map<String, ?>) obj) : new JSONObject(obj.toString()); // instrumentation DelayProfiler.updateDelay("lookupEntireRecord", startTime); // older style int lookupTime = (int) (System.currentTimeMillis() - startTime); if (lookupTime > 20) { DatabaseConfig.getLogger().log(Level.FINE, "{0} mongoLookup Long delay {1}", new Object[] { dbName, lookupTime }); } return json; } else { throw new RecordNotFoundException(guid); } } catch (JSONException e) { DatabaseConfig.getLogger().log(Level.WARNING, "{0} Unable to parse JSON: {1}", new Object[] { dbName, e.getMessage() }); return null; } catch (MongoException e) { DatabaseConfig.getLogger().log(Level.FINE, "{0} lookupEntireRecord failed: {1}", new Object[] { dbName, e.getMessage() }); throw new FailedDBOperationException(collectionName, guid, "Original mongo exception:" + e.getMessage()); } finally { db.requestDone(); } }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
private MongoRecordCursor selectRecords(String collectionName, ColumnField valuesMapField, String key, Object value, boolean explain) throws FailedDBOperationException { db.requestEnsureConnection();/*from w w w.j a v a 2 s . co m*/ DBCollection collection = db.getCollection(collectionName); // note that if the value of the key in the database is a list (which it is) this // query will find all records where the value (a list) *contains* an element whose value is the value // //FROM MONGO DOC: Match an Array Element //Equality matches can specify a single element in the array to match. These specifications match //if the array contains at least one element with the specified value. //In the following example, the query matches all documents where the value of the field tags is //an array that contains 'fruit' as one of its elements: //db.inventory.find( { tags: 'fruit' } ) String fieldName = valuesMapField.getName() + "." + key; BasicDBObject query = new BasicDBObject(fieldName, value); //System.out.println("***GNSProtocol.QUERY.toString()***: " + query.toString()); DBCursor cursor = null; try { cursor = collection.find(query); } catch (MongoException e) { DatabaseConfig.getLogger().log(Level.FINE, "{0} selectRecords failed: {1}", new Object[] { dbName, e.getMessage() }); throw new FailedDBOperationException(collectionName, fieldName, "Original mongo exception:" + e.getMessage()); } if (explain) { System.out.println(cursor.explain().toString()); } return new MongoRecordCursor(cursor, mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey()); }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
private MongoRecordCursor selectRecordsWithin(String collectionName, ColumnField valuesMapField, String key, String value, boolean explain) throws FailedDBOperationException { db.requestEnsureConnection();// w ww . j av a 2 s . com DBCollection collection = db.getCollection(collectionName); BasicDBList box = parseJSONArrayLocationStringIntoDBList(value); String fieldName = valuesMapField.getName() + "." + key; BasicDBObject shapeClause = new BasicDBObject("$box", box); BasicDBObject withinClause = new BasicDBObject("$geoWithin", shapeClause); BasicDBObject query = new BasicDBObject(fieldName, withinClause); DBCursor cursor = null; try { cursor = collection.find(query); } catch (MongoException e) { DatabaseConfig.getLogger().log(Level.FINE, "{0} selectRecordsWithin failed: {1}", new Object[] { dbName, e.getMessage() }); throw new FailedDBOperationException(collectionName, fieldName, "Original mongo exception:" + e.getMessage()); } if (explain) { System.out.println(cursor.explain().toString()); } return new MongoRecordCursor(cursor, mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey()); }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
private MongoRecordCursor selectRecordsNear(String collectionName, ColumnField valuesMapField, String key, String value, Double maxDistance, boolean explain) throws FailedDBOperationException { db.requestEnsureConnection();// w w w .ja v a2s .c o m DBCollection collection = db.getCollection(collectionName); double maxDistanceInRadians = maxDistance / METERS_PER_DEGREE; BasicDBList tuple = new BasicDBList(); try { JSONArray json = new JSONArray(value); tuple.add(json.getDouble(0)); tuple.add(json.getDouble(1)); } catch (JSONException e) { DatabaseConfig.getLogger().log(Level.SEVERE, "{0} Unable to parse JSON: {1}", new Object[] { dbName, e.getMessage() }); } String fieldName = valuesMapField.getName() + "." + key; BasicDBObject nearClause = new BasicDBObject("$near", tuple).append("$maxDistance", maxDistanceInRadians); BasicDBObject query = new BasicDBObject(fieldName, nearClause); DBCursor cursor = null; try { cursor = collection.find(query); } catch (MongoException e) { DatabaseConfig.getLogger().log(Level.FINE, "{0} selectNear failed: {1}", new Object[] { dbName, e.getMessage() }); throw new FailedDBOperationException(collectionName, fieldName, "Original mongo exception:" + e.getMessage()); } if (explain) { System.out.println(cursor.explain().toString()); } return new MongoRecordCursor(cursor, mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey()); }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
private MongoRecordCursor selectRecordsQuery(String collectionName, ColumnField valuesMapField, String query, List<String> projection, boolean explain) throws FailedDBOperationException { db.requestEnsureConnection();/*from w w w . jav a2 s . c om*/ DBCollection collection = db.getCollection(collectionName); DBCursor cursor = null; try { if (projection == null // this handles the special case of the user wanting all fields // in the projection || (!projection.isEmpty() && projection.get(0).equals(GNSProtocol.ENTIRE_RECORD.toString()))) { cursor = collection.find(parseMongoQuery(query, valuesMapField)); } else { cursor = collection.find(parseMongoQuery(query, valuesMapField), generateProjection(projection)); } } catch (MongoException e) { DatabaseConfig.getLogger().log(Level.FINE, "{0} selectRecordsQuery failed: {1}", new Object[] { dbName, e.getMessage() }); throw new FailedDBOperationException(collectionName, query, "Original mongo exception:" + e.getMessage()); } if (explain) { System.out.println(cursor.explain().toString()); } return new MongoRecordCursor(cursor, mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey()); }
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); });/* w ww . ja v a 2s . 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; }