List of usage examples for com.mongodb DBCollection find
public DBCursor find(@Nullable final DBObject query, final DBCollectionFindOptions options)
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.j a 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.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 ww w . j av a 2 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.eharmony.matching.seeking.executor.mongodb.MongoQueryExecutor.java
License:Apache License
@VisibleForTesting protected DBCursor find(DBCollection collection, DBObject query, DBObject fields) { // Collection.find is final, this is wrapped to allow unit testing. return collection.find(query, fields); }
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 w w . ja v a 2 s . 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; }
From source file:com.foodtruckdata.mongodb.UsersInput.java
@Override public void FollowTruck(String truck_id, String user_id) { BasicDBObject filter = new BasicDBObject("_id", new ObjectId(truck_id)); DBCollection coll = mongoDB.getCollection("Trucks"); Cursor cursor = coll.find(filter, (new BasicDBObject("$elemMatch", new BasicDBObject("Followers", new ObjectId(user_id))))); if (!cursor.hasNext()) { coll.update(filter, (new BasicDBObject("$addToSet", (new BasicDBObject("Trucks.Followers", new BasicDBObject("_id", new ObjectId(user_id))))))); }/* w w w. j a va 2 s .com*/ }
From source file:com.github.nlloyd.hornofmongo.adaptor.Mongo.java
License:Open Source License
@JSFunction public Object find(final String ns, final Object query, final Object fields, Integer limit, Integer skip, Integer batchSize, Integer options) { Object result = null;// w w w. j a va2 s . c om Object rawQuery = BSONizer.convertJStoBSON(query, false); Object rawFields = BSONizer.convertJStoBSON(fields, false); DBObject bsonQuery = null; DBObject bsonFields = null; if (rawQuery instanceof DBObject) bsonQuery = (DBObject) rawQuery; if (rawFields instanceof DBObject) bsonFields = (DBObject) rawFields; com.mongodb.DB db = innerMongo.getDB(ns.substring(0, ns.indexOf('.'))); String collectionName = ns.substring(ns.indexOf('.') + 1); if ("$cmd".equals(collectionName)) { try { if (options == 0) options = innerMongo.getOptions(); //GC: 16/11/15 fixed for v3 // CommandResult cmdResult = db.command(bsonQuery, options, CommandResult cmdResult = db.command(bsonQuery, innerMongo.getReadPreference(), HornOfMongoBSONEncoder.FACTORY.create()); //GC: 16/11/15 removed for v3 // handlePostCommandActions(db, bsonQuery); Object jsCmdResult = BSONizer.convertBSONtoJS(mongoScope, cmdResult); result = MongoRuntime .call(new NewInstanceAction(mongoScope, "InternalCursor", new Object[] { jsCmdResult })); } catch (NoSuchElementException nse) { // thrown when db.runCommand() called (no arguments) CommandResult failedCmdResult = db.command(this.hosts.iterator().next().toString()); failedCmdResult.put("ok", Boolean.FALSE); failedCmdResult.put("errmsg", "no such cmd: "); Object jsFailedCmdResult = BSONizer.convertBSONtoJS(mongoScope, failedCmdResult); result = MongoRuntime.call( new NewInstanceAction(mongoScope, "InternalCursor", new Object[] { jsFailedCmdResult })); } catch (MongoException me) { handleMongoException(me); } } else { DBCollection collection = db.getCollection(collectionName); collection.setDBEncoderFactory(HornOfMongoBSONEncoder.FACTORY); collection.setDBDecoderFactory(HornOfMongoBSONDecoder.FACTORY); DBObject specialFields = null; if (bsonQuery.get("query") instanceof DBObject) { specialFields = bsonQuery; bsonQuery = (DBObject) bsonQuery.get("query"); } DBCursor cursor = collection.find(bsonQuery, bsonFields).skip(skip).batchSize(batchSize).limit(limit) .addOption(options); if (specialFields != null) { for (String key : specialFields.keySet()) { if (!"query".equals(key)) cursor.addSpecial(key, specialFields.get(key)); } } InternalCursor jsCursor = (InternalCursor) MongoRuntime .call(new NewInstanceAction(mongoScope, "InternalCursor", new Object[] { cursor })); result = jsCursor; } return result; }
From source file:com.hangum.tadpole.mongodb.core.composite.result.MongodbResultComposite.java
License:Open Source License
/** * ? ? .// ww w . j a va 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 av a2 s.co 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:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java
License:Open Source License
/** * GridFS chunck detail information//from w w w . j av a2s . c om * * @param userDB * @param objectId * @return * @throws Exception */ public static DBCursor getGridFSChunckDetail(UserDBDAO userDB, String searchChunkName, String objectId) throws Exception { DBCollection col = findCollection(userDB, searchChunkName); // DBObject queryObj = new BasicDBObject(); queryObj.put("files_id", new ObjectId(objectId)); // field DBObject fieldObj = new BasicDBObject(); fieldObj.put("files_id", 1); fieldObj.put("n", 1); return col.find(queryObj, fieldObj); }
From source file:com.hangum.tadpole.mongodb.core.test.MongoTestAndStmt.java
License:Open Source License
/** * @param args//from www . jav a2s.com */ public static void main(String[] args) throws Exception { ConAndAuthentication testMongoCls = new ConAndAuthentication(); Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port); DB db = mongo.getDB("test"); DBCollection myColl = db.getCollection("city1"); // show column BasicDBObject myColumn = new BasicDBObject(); myColumn.put("loc.y", true); // where BasicDBObject myAndQuery = new BasicDBObject(); // myAndQuery.append("rental_id", new BasicDBObject("$gte", 1)); // myAndQuery.append("inventory_id", 367);//new BasicDBObject("$eq", 367)); DBCursor myCursor = myColl.find(myAndQuery, myColumn); while (myCursor.hasNext()) { System.out.println(myCursor.next()); } mongo.close(); }