public void Practice2() { BasicDBObject note; BasicDBObject course_id; List<BasicDBObject> obj; List<Double> courselist = new ArrayList<Double>(); DBCollection dBCollection = db.getCollection("course"); BasicDBObject query = new BasicDBObject("name", "math"); BasicDBObject fields = new BasicDBObject("_id", 1); DBCursor cursor = dBCollection.find(query, fields); try { while (cursor.hasNext()) { courselist.add((Double) cursor.next().get("_id")); } } finally { cursor.close(); } dBCollection = db.getCollection("student"); note = new BasicDBObject("final", new BasicDBObject("$gt", 4)); for (int i = 0; i < courselist.size(); i++) { obj = new ArrayList<BasicDBObject>(); obj.add(note); course_id = new BasicDBObject("course_id", courselist.get(i)); obj.add(course_id); query = new BasicDBObject("$and", obj); fields = new BasicDBObject("last_name", 1); cursor = dBCollection.find(query, fields); try { while (cursor.hasNext()) { System.out.println(cursor.next().get("last_name")); } } finally { cursor.close(); } } }
public void Practice3() { List<String> courselist = new ArrayList<String>(); double id = 0; DBCollection dBCollection = db.getCollection("teacher"); BasicDBObject query = new BasicDBObject("last_name", "rodriguez"); BasicDBObject fields = new BasicDBObject("_id", 1); DBCursor cursor = dBCollection.find(query, fields); try { if (cursor.hasNext()) { id = (Double) cursor.next().get("_id"); } } finally { cursor.close(); } dBCollection = db.getCollection("course"); query = new BasicDBObject("teacher", id); fields = new BasicDBObject("name", 1); cursor = dBCollection.find(query, fields); try { while (cursor.hasNext()) { courselist.add((String) cursor.next().get("name")); } } finally { cursor.close(); } Collections.sort(courselist); for (int i = 0; i < courselist.size(); i++) { System.out.println(courselist.get(i)); } }
@Override public ArrayList<Status> listStatus() { try { mdc.connectionPool(); try { cursor = mdc.findCollection("Status"); while (cursor.hasNext()) { System.out.println(); status.add( new Status( Integer.parseInt(cursor.next().get("StatusId").toString()), cursor.next().get("StatusName").toString())); } } finally { cursor.close(); } } catch (UnknownHostException ex) { java.util.logging.Logger.getLogger(StatusDaoImpl.class.getName()) .log(java.util.logging.Level.SEVERE, "Get Status", ex); } return status; }
public JsonArray getPerfResults(String perfResults) { DBCollection coll = db.getCollection("performance"); BasicDBObject query = new BasicDBObject(); BasicDBObject removeId = new BasicDBObject("_id", 0); query.put("name", perfResults); DBCursor cursor = coll.find(query, removeId); JsonObjectBuilder objBuild = Json.createObjectBuilder(); JsonArrayBuilder arrBuild = Json.createArrayBuilder(); JsonObject json = objBuild.build(); while (cursor.hasNext()) { BasicDBObject found = (BasicDBObject) cursor.next(); LOG.info("Found Performance Results: " + found.toString()); json = Json.createReader(new StringReader(found.toString())).readObject(); arrBuild.add(json); } LOG.info( "----------------------------------- ARR BUILD -------------------------------------------------\n" + arrBuild.build().toString()); return arrBuild.build(); }
/** * 上午11:27:09 * * @author zhangyh2 DBMongo.java TODO 查找全部地址信息 * @return */ public static List<AddressModel> selectAllAddress(String token) { // TODO Auto-generated method stub DBCollection collection = DBMongo.getInstance().getDB().getCollection(tablename); DBCursor dbObject = collection.find(new BasicDBObject("token", token)); try { // 增删查改必须放到线程中进行。否则报错。 List<AddressModel> data = new ArrayList<AddressModel>(); while (dbObject.hasNext()) { DBObject ob = dbObject.next(); data.add( new AddressModel( ob.get("_id").toString(), ob.get("name").toString(), ob.get("tel").toString(), ob.get("province").toString(), ob.get("city").toString(), ob.get("district").toString(), ob.get("zipcode").toString(), ob.get("token").toString())); } return data; } catch (Exception e) { // TODO: handle exception } finally { if (dbObject != null) { dbObject.close(); } } return null; }
/** * 获取指定分页数据记录用于下载 * * @author felixsion * */ @Override public List<YandeCG> getTenNumFileToDownLoad(int startPags, int endPages) { List<YandeCG> yandeCGList = new ArrayList<YandeCG>(); DBCursor cur = collection.find(new BasicDBObject("downComplete", Boolean.FALSE)); int num = 0; while (cur.hasNext() && num >= startPags && num < endPages) { DBObject dBObject = cur.next(); System.out.println(dBObject); ++num; YandeCG yanedCG = new YandeCG(); yanedCG.setId(Integer.parseInt(dBObject.get("id").toString())); yanedCG.setTags(dBObject.get("tags").toString()); yanedCG.setMd5(dBObject.get("md5").toString()); yanedCG.setDownComplete(Boolean.parseBoolean(dBObject.get("downComplete").toString())); yanedCG.setSource(dBObject.get("source").toString()); yanedCG.setFile_url(dBObject.get("file_url").toString()); yanedCG.setFile_size(dBObject.get("file_size").toString()); yandeCGList.add(yanedCG); logger.info("已经获取到第 " + num + " 个未下载任务 图像ID:" + dBObject.get("id").toString()); } /** 判断是否已经加载数据* */ if (num == 0) { logger.warn("未获取到未下载数据列表 此次获取未下载数据失败 检查数据库是否为全部下载状态"); } cur.close(); return yandeCGList; }
@Override public void getLocations() { final BasicDBObject query = new BasicDBObject(); final BasicDBObject fields = new BasicDBObject(); query.put("Request details.Request type", POST); query.put("Request details.Reply code", SUCCESS_REPLY_CODE); fields.put("Host location", 1); fields.put("Server details.Server location", 1); fields.put("_id", 0); final DBCursor result = table.find(query, fields); final StringBuilder locations = new StringBuilder(); while (result.hasNext()) { final String hostLocation = (String) result.next().get("Host location"); final BasicDBObject requestDetails = (BasicDBObject) result.curr().get("Server details"); final String serverLocation = requestDetails.getString("Server location"); locations.append(hostLocation + " - " + serverLocation + "\n"); } System.out.println("getLocations:"); System.out.println(locations); }
public void addCardInfoToNeo4j() { DBCursor cursor = cardCollection.find(); DBObject sortObject = new BasicDBObject(); sortObject.put("name", 1); // cursor = cursor.sort(sortObject); cursor.addOption(Bytes.QUERYOPTION_NOTIMEOUT); int count = 0; while (cursor.hasNext()) { DBObject cardObject = cursor.next(); String cardName = cardObject.get("name").toString().toUpperCase(); if (cardNodes.get(cardName) == null) { Node newCardNode = graphDb.createNode(); newCardNode.setProperty("name", cardName); for (String property : cardObject.keySet()) { if (!property.equalsIgnoreCase("name")) { newCardNode.setProperty(property, cardObject.get(property).toString()); } } cardNodes.put(cardName, newCardNode); } else { Node node = cardNodes.get(cardName); for (String property : cardObject.keySet()) { if (!property.equalsIgnoreCase("name")) { node.setProperty(property, cardObject.get(property).toString()); } } } count++; System.out.println("Processed " + count + " card"); } }
/** Loads the list of commands from one game */ @Override public List<Object> getAll(int gameID) { try { db.start(); DBCollection collection = db.getDB().getCollection("moves"); XStream xStream = new XStream(); DBCursor cursor = collection.find(); if (cursor == null) return null; List<Object> commands = new ArrayList<Object>(); while (cursor.hasNext()) { DBObject obj = cursor.next(); String xml = (String) obj.get(Integer.toString(gameID)); if (xml != null) commands.add((Object) xStream.fromXML(xml)); } db.stop(true); return commands; } catch (Exception e) { e.printStackTrace(); return null; } }
public static void main(String[] args) throws UnknownHostException { System.out.println("Start Testing"); MongoClient client = new MongoClient(new ServerAddress("192.168.0.14", 27017)); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findTestFromJava"); collection.drop(); for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("x", new Random().nextInt(100))); } System.out.println("Find one:"); DBObject one = collection.findOne(); System.out.println("one = " + one); System.out.println("\nFind all:"); DBCursor cursor = collection.find(); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println("cursor = " + cur); } } finally { cursor.close(); } System.out.println("\nFind Count:"); long count = collection.count(); System.out.println("count = " + count); }
private String selectBooks( String schema, String collection, String title, String author, String isbn) throws UnknownHostException { System.out.println(schema); System.out.println(collection); System.out.println(title); System.out.println(author); List<String> l = new ArrayList<String>(); MongoDBConnectionManager mgr = MongoDBConnectionManager.getInstance(); Mongo mongo = mgr.getMongo(); DB db = mongo.getDB(schema); try { DBCollection c = db.getCollection(collection); BasicDBObject titleQuery = new BasicDBObject(); titleQuery.put("title", new BasicDBObject("$regex", title)); BasicDBObject authorQuery = new BasicDBObject(); authorQuery.put("author", new BasicDBObject("$regex", author)); BasicDBList or = new BasicDBList(); or.add(titleQuery); or.add(titleQuery); DBObject query = new BasicDBObject("$and", or); DBCursor cursor = c.find(titleQuery); while (cursor.hasNext()) l.add(cursor.next().toString()); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println(l); if (l.size() > 0) return l.toString(); else return null; }
private String selectBooks(String collectionType, String type, String text, String schema) throws UnknownHostException { System.out.println(type); System.out.println(schema); List<String> l = new ArrayList<String>(); MongoDBConnectionManager mgr = MongoDBConnectionManager.getInstance(); Mongo mongo = mgr.getMongo(); DB db = mongo.getDB(schema); // collectionType = "view" try { DBCollection collection = db.getCollection(collectionType); BasicDBObject searchQuery = new BasicDBObject(); BasicDBObject regexQuery = new BasicDBObject(); // regexQuery.put("title", new BasicDBObject("$regex", "^.*mi.*$").append("$options", "i")); regexQuery.put(type, new BasicDBObject("$regex", text).append("$options", "i")); DBCursor cursor = collection.find(regexQuery); while (cursor.hasNext()) l.add(cursor.next().toString()); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println(l); if (l.size() > 0) return l.toString(); return "error"; }
@Override public List<IngestedLog> getLogs() { List<IngestedLog> logs = new ArrayList<IngestedLog>(); DBCursor cursor = collection.find(); while (cursor.hasNext()) logs.add(new MongoIngestedLog(cursor.next())); return logs; }
/** 分页查询 */ @Test public void pageQuery() { DBCursor cursor = bakFiles.find().skip(0).limit(10); while (cursor.hasNext()) { System.out.println(cursor.next()); } }
public static Double connect(String s) { double score = 0; try { System.out.println("in mongo"); // mongoClient = new MongoClient("localhost", 27017); // @SuppressWarnings("deprecation") DB db = mongoClient.getDB("rank"); coll = db.getCollection("rankTable"); while (true) { // System.out.println("SEARCH"); // Scanner sc = new Scanner(System.in); // String m = sc.nextLine(); BasicDBObject q = new BasicDBObject(); q.put("path", s); DBCursor cursor = coll.find(q); while (cursor.hasNext()) { score = (double) cursor.next().get("score"); } } } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } // mongoClient.close(); return score; }
private List<JobInstance> mapJobInstances(DBCursor dbCursor) { List<JobInstance> results = new ArrayList<JobInstance>(); while (dbCursor.hasNext()) { results.add(mapJobInstance(dbCursor.next())); } return results; }
public static void main(String[] args) throws UnknownHostException { Mongo client = new Mongo(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("sortSkipLimitSample"); lines.drop(); Random rand = new Random(); // insert 10 lines with random start and end points for (int i = 0; i < 10; i++) { lines.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(90) + 10))); } DBCursor cursor = lines.find().sort(new BasicDBObject("start.x", 1).append("start.y", -1)).skip(2).limit(10); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB courseDB = client.getDB("course"); DBCollection list = courseDB.getCollection("DotNotationTest"); list.drop(); Random random = new Random(); for (int i = 0; i < 10; i++) { list.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", random.nextInt(2)).append("y", random.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", random.nextInt(2)).append("y", random.nextInt(90) + 10))); } DBCursor cursor = list.find().sort(new BasicDBObject("start.x", 1).append("start.y", -1)).skip(2).limit(10); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
@Override public void run() { MongoProfile profile = options.getProfile(); MongoClient mongo = null; DBCursor cursor = null; try { mongo = new MongoClient(profile.getAddress(), profile.getCredentials()); DB db = mongo.getDB(options.getDatabase()); DBCollection col = db.getCollection(options.getCollection()); cursor = col.find(); while (cursor.hasNext()) { DBObject doc = cursor.next(); Map<String, Object> m = convert(doc); pushPipe(new Row(m)); } } catch (Throwable t) { slog.error("araqne logdb mongo: cannot run mongo.find", t); } finally { if (cursor != null) cursor.close(); if (mongo != null) mongo.close(); } }
ArrayList<Person> Load_GroupList(String G_Name) { ArrayList<Person> PersonList = new ArrayList<Person>(); GroupColl = AdressDB.getCollection(G_Name); if (GroupColl.getCount() != 0) { DBCursor cur; cur = GroupColl.find(); while (cur.hasNext()) { Person P_Temp = new Person(); P_Temp.ObjectID = cur.next().get("_id").toString(); P_Temp.Name = cur.curr().get("name").toString(); P_Temp.Mail_Address = cur.curr().get("mail").toString(); P_Temp.Phone = cur.curr().get("phone").toString(); PersonList.add(P_Temp); } } else { System.out.println("그룹에 사람 없음"); } return PersonList; }
private void getTweetWithRTCountGreaterThan(int gt) { Mongo mongo = null; try { mongo = new Mongo(MONGO_DB_HOST, MONGO_DB_PORT); DB db = mongo.getDB(MONGO_DB_NAME); DBCollection collection = db.getCollection(MONGO_DB_COLLECTION); DBCursor cursor = collection.find(new BasicDBObject("rTCount", new BasicDBObject("$gt", gt))); DBObject dbObject; System.out.println("\n\n========================================"); System.out.println("Displaying Tweet with RTCount > " + gt); while (cursor.hasNext()) { dbObject = cursor.next(); System.out.println( "user " + dbObject.get("user") + "tweet " + dbObject.get("tweet") + " RTCount " + dbObject.get("rTCount")); } System.out.println("========================================\n\n"); } catch (UnknownHostException e) { e.printStackTrace(); } finally { if (mongo != null) mongo.close(); } }
ArrayList<To_Sender_Person> Load_Sender_Person(Long Time, int num) { ArrayList<To_Sender_Person> Sender_Person_List = new ArrayList<To_Sender_Person>(); DBCursor Personcur; SendMailColl = SendMailDB.getCollection(Time.toString()); Personcur = SendMailColl.find(new BasicDBObject("sending", false)); if (Personcur.count() != 0) { for (int i = 0; i < num; i++) { if (!Personcur.hasNext()) break; To_Sender_Person Temp_Person = new To_Sender_Person(); Temp_Person.ObjectID = Personcur.next().get("_id").toString(); Temp_Person.To_Adress = Personcur.curr().get("toaddress").toString(); Temp_Person.Key = Integer.parseInt(Personcur.curr().get("key").toString()); Sender_Person_List.add(Temp_Person); } } Boolean True; True = true; for (To_Sender_Person person : Sender_Person_List) { BasicDBObject newDocument3 = new BasicDBObject().append("$set", new BasicDBObject().append("sending", True)); ObjectId id = new ObjectId(person.ObjectID); SendMailColl.update(new BasicDBObject().append("_id", id), newDocument3); } return Sender_Person_List; }
/** * 查询YandeCG表中所有文件 * * @author felixerio * */ @Override public List<YandeCG> listAllYandeCG() { try { List<YandeCG> yandeCGList = new ArrayList<YandeCG>(); DBCursor cur = collection.find(); int num = 1; while (cur.hasNext()) { YandeCG yanedCG = new YandeCG(); DBObject dBObject = cur.next(); yanedCG.setId(Integer.parseInt(dBObject.get("id").toString())); yanedCG.setTags(dBObject.get("tags").toString()); yanedCG.setMd5(dBObject.get("md5").toString()); yanedCG.setDownComplete(Boolean.parseBoolean(dBObject.get("downComplete").toString())); yanedCG.setSource(dBObject.get("source").toString()); yanedCG.setFile_url(dBObject.get("file_url").toString()); yanedCG.setFile_size(dBObject.get("file_size").toString()); yandeCGList.add(yanedCG); num++; } logger.info("批量获取全部数据数据任务 完成处理 " + num + " 个任务"); cur.close(); return yandeCGList; } catch (Exception e) { logger.error(e.getMessage()); } return null; }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection collection = db.getCollection("findCriteriaTest"); collection.drop(); for (int i = 0; i < 10; i++) { collection.insert( new BasicDBObject("x", new Random().nextInt(2)).append("y", new Random().nextInt(100))); } QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(90); // DBObject query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt", // 10).append("$lt", 90)); System.out.println("\nCount:"); long count = collection.count(builder.get()); System.out.println(count); System.out.println("\nFind all:"); DBCursor cursor = collection.find(builder.get()); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }
@Override public Page<Role2> findAll(String searchText, Pageable pageable) { final BasicDBObject query; if (!Strings.isNullOrEmpty(searchText)) { query = getQueryBySearchText(searchText); } else { query = new BasicDBObject(); } final BasicDBObject fields = new BasicDBObject(); final BasicDBObject sortQuery = MongoUtils.getSort(pageable.getSort(), "modificationTime", Sort.Direction.DESC); final DBCursor dbCursor = rolePersonColl .find(query, fields, (int) pageable.getOffset(), (int) pageable.getPageSize()) .sort(sortQuery); final List<Role2> roleList = new ArrayList<>(); while (dbCursor.hasNext()) { final DBObject dbObject = dbCursor.next(); final Role2 role = new DBObjectToEntity().apply(dbObject); roleList.add(role); } final long total = count(searchText); return new PageImpl<>(roleList, pageable, total); }
@Test public void testBasicQuery() { BasicDBObject query = new BasicDBObject(); query.put(EmployeeProperties.EMPLOYEE_ID, "28241"); BasicDBObject fields = new BasicDBObject(); fields.put(EmployeeProperties.ID, 0); fields.put(EmployeeProperties.LAST_NAME, 1); fields.put(EmployeeProperties.EMPLOYEE_ID, 1); DBCollection collection = mongoOps.getCollection(EmployeeProperties.COLLECTION); log.info( "MongoDB Query Explain Plan: " + collection .find(query, fields) .hint(new BasicDBObject(EmployeeProperties.EMPLOYEE_ID, 1)) .explain()); DBCursor cursor = collection.find(query, fields).hint(new BasicDBObject(EmployeeProperties.EMPLOYEE_ID, 1)); log.info(cursor.count() + ""); assertNotNull("cursor was null.", cursor); assertEquals("cursor count was not 1.", 1, cursor.count()); log.info("Query (" + query.toString() + ")"); while (cursor.hasNext()) { DBObject dbo = cursor.next(); log.info(dbo.toString()); assertEquals("Keyset size not equal to 2.", 2, dbo.keySet().size()); } log.info(cursor.explain().toString()); }
@Override public String Json(String nombreDB, int clienteId) throws UnknownHostException, JSONException { // TODO Auto-generated method stub MongoClient mongoClient = new MongoClient("localhost", 27017); DB base = mongoClient.getDB(nombreDB); DBCollection collection = base.getCollection("Json"); BasicDBObject query = new BasicDBObject(); query.put("id", clienteId); DBCursor cursor = collection.find(query); if (cursor.size() == 0) { // System.out.println("********************\n"); // System.out.println("No existe el cliente, no se puede ingresar json"); // System.out.println("********************\n"); return "No existe el cliente, no se puede ingresar json"; } // Existe el cliente DBObject objeto = (DBObject) cursor.next(); DBObject json = (DBObject) objeto.get("json"); // DBObject j = JSON.parse(json.toString()); JSONObject aj = new JSONObject(json.toString()); return aj.toString(); }
public static String getLogList(String userID) { DBCursor cursor = collLog .find( (DBObject) JSON.parse( "{ $or : [ { userID : \"" + userID + "\"}, {users: \"" + userID + "\" }]}"), (DBObject) JSON.parse("{ _id : 0, nodeID : 0, users : 0 }")) .sort((DBObject) JSON.parse("{ time : -1 }")); JsonArray logArray = new JsonArray(); try { while (cursor.hasNext()) { String data = cursor.next().toString(); JsonObject jsonObj = new JsonObject(data); System.out.println(data); logArray.addObject(jsonObj); } } finally { cursor.close(); } JsonObject logList = new JsonObject(); logList.putArray("log", logArray); return logList.encode(); }
public JsonArray addPerfResults(String perfResults) { DBCollection coll = db.getCollection("performance"); BasicDBObject newPerfResults = (BasicDBObject) JSON.parse(perfResults); newPerfResults.append("_id", newPerfResults.getString("name")); BasicDBObject query = new BasicDBObject(); query.append("name", newPerfResults.getString("name")); BasicDBObject removeId = new BasicDBObject("_id", 0); DBCursor cursor = coll.find(query, removeId); JsonObjectBuilder objBuild = Json.createObjectBuilder(); JsonArrayBuilder arrBuild = Json.createArrayBuilder(); JsonObject json = objBuild.build(); if (cursor.count() > 0) { LOG.info("Performance Results Found: "); BasicDBObject found = (BasicDBObject) cursor.next(); json = Json.createReader(new StringReader(found.toString())).readObject(); arrBuild.add(json); } else { LOG.info("New Performance Results Created: " + coll.insert(newPerfResults)); json = Json.createReader(new StringReader(newPerfResults.toString())).readObject(); arrBuild.add(json); } LOG.info( "----------------------------------- ARR BUILD -------------------------------------------------\n" + arrBuild.build().toString()); return arrBuild.build(); }
public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient(); DB db = client.getDB("course"); DBCollection lines = db.getCollection("dotNotationTest"); lines.drop(); Random rand = new Random(); for (int i = 0; i < 10; i++) { lines.insert( new BasicDBObject("_id", i) .append( "start", new BasicDBObject("x", rand.nextInt(90) + 10).append("y", rand.nextInt(90) + 10)) .append( "end", new BasicDBObject("x", rand.nextInt(90) + 10) .append("y", rand.nextInt(90) + 10))); } QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50); DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true).append("_id", false)); try { while (cursor.hasNext()) { DBObject cur = cursor.next(); System.out.println(cur); } } finally { cursor.close(); } }