// 0이 이하 1이 이상 두개다 날짜면 사이 ArrayList<Send_Mail> Load_Mail_List(long day, long checkday) { DBCursor cur; SendMailColl = SendMailDB.getCollection("Mail_Content"); System.out.println(SendMailColl.getCount()); // 이하 // cur = SendMailColl.find(new BasicDBObject().append("id", new // BasicDBObject((checkday == 0 ? "$lte" : "$gte"), day)));// <= 상혁이꺼 if (checkday == 0) { cur = SendMailColl.find( new BasicDBObject().append("time", new BasicDBObject("$lte", day))); // <= return Add_Mail_List(cur); } // 이상 else if (checkday == 1) { cur = SendMailColl.find( new BasicDBObject().append("time", new BasicDBObject("$gte", day))); // >= return Add_Mail_List(cur); } // 사이값 else { BasicDBObject query = new BasicDBObject(); query.append("time", new BasicDBObject("$gte", day)); query.append("time", new BasicDBObject("$lte", checkday)); cur = SendMailColl.find(query); return Add_Mail_List(cur); } }
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(); } } }
private void addQueryToStream( final Operation operation, final Timestamp<?> currentTimestamp, final DBObject update, final String collection) throws InterruptedException { if (logger.isTraceEnabled()) { logger.trace( "addQueryToStream - operation [{}], currentTimestamp [{}], update [{}]", operation, currentTimestamp, update); } if (collection == null) { for (String name : slurpedDb.getCollectionNames()) { DBCollection slurpedCollection = slurpedDb.getCollection(name); for (DBObject item : slurpedCollection.find(update, findKeys)) { addToStream(operation, currentTimestamp, item, collection); } } } else { DBCollection slurpedCollection = slurpedDb.getCollection(collection); for (DBObject item : slurpedCollection.find(update, findKeys)) { addToStream(operation, currentTimestamp, item, collection); } } }
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)); } }
@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()); }
public static void main(String[] args) throws UnknownHostException, MongoException { Mongo mongo = null; try { mongo = new Mongo("localhost"); DB db = mongo.getDB("test"); DBCollection collection = db.getCollection("foo"); DBCursor cursor = collection.find(); while (cursor.hasNext()) { DBObject dbObject = (DBObject) cursor.next(); // System.err.println(dbObject); } DBCursor cursor1 = collection.find(); Page<DBObject> result = PaginationHelper.paginate(cursor1, 2, 10); for (DBObject dbObject : cursor1) { System.err.println(dbObject); } System.err.println(result.getTotalElements()); } finally { if (mongo != null) { mongo.close(); } } }
protected void doFindAll(Exchange exchange) throws Exception { DBCollection dbCol = calculateCollection(exchange); // do not use getMandatoryBody, because if the body is empty we want to retrieve all objects in // the collection DBObject query = null; // do not run around looking for a type converter unless there is a need for it if (exchange.getIn().getBody() != null) { query = exchange.getIn().getBody(DBObject.class); } DBObject fieldFilter = exchange.getIn().getHeader(MongoDbConstants.FIELDS_FILTER, DBObject.class); // get the batch size and number to skip Integer batchSize = exchange.getIn().getHeader(MongoDbConstants.BATCH_SIZE, Integer.class); Integer numToSkip = exchange.getIn().getHeader(MongoDbConstants.NUM_TO_SKIP, Integer.class); Integer limit = exchange.getIn().getHeader(MongoDbConstants.LIMIT, Integer.class); DBObject sortBy = exchange.getIn().getHeader(MongoDbConstants.SORT_BY, DBObject.class); DBCursor ret = null; try { if (query == null && fieldFilter == null) { ret = dbCol.find(new BasicDBObject()); } else if (fieldFilter == null) { ret = dbCol.find(query); } else { ret = dbCol.find(query, fieldFilter); } if (sortBy != null) { ret.sort(sortBy); } if (batchSize != null) { ret.batchSize(batchSize.intValue()); } if (numToSkip != null) { ret.skip(numToSkip.intValue()); } if (limit != null) { ret.limit(limit.intValue()); } Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.findAll); resultMessage.setBody(ret.toArray()); resultMessage.setHeader(MongoDbConstants.RESULT_TOTAL_SIZE, ret.count()); resultMessage.setHeader(MongoDbConstants.RESULT_PAGE_SIZE, ret.size()); } finally { // make sure the cursor is closed if (ret != null) { ret.close(); } } }
/** * 查询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; }
/** * 获取数据库总条数 * * @author felixsion * */ @Override public int getDataBaseCollectionToyalNum() { DBCursor cur = collection.find(); int num = cur.size(); cur.close(); return num; }
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; }
@Override protected void setUp() throws Exception { mongo = new Mongo("127.0.0.1", 8888); db = mongo.getDB("test"); dbco = db.getCollection("test"); cursor = dbco.find(); }
@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 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 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"); } }
@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); }
/** 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; } }
@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(); } }
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 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(); } }
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(); }
/** * 获取指定分页数据记录用于下载 * * @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; }
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; }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); MongoClientURI uri = new MongoClientURI("mongodb://*****:*****@ds019028.mlab.com:19028/asedb"); MongoClient client = new MongoClient(uri); DB db = client.getDB(uri.getDatabase()); DBCollection users = db.getCollection("UserRecords"); BasicDBObject query = new BasicDBObject(); String firstname = request.getParameter("FirstName"); String lastname = request.getParameter("LastName"); String email = request.getParameter("email"); String password = request.getParameter("EnterPassword"); String confpasswd = request.getParameter("ConfirmPassword"); query.put("First Name", firstname); query.put("Last Name", lastname); query.put("Email", email); System.out.println(email); if (password == confpasswd) { query.put("Password", password); } else { } DBCursor docs = users.find(query); response.getWriter().write(docs.toArray().toString()); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); System.out.println("Insert doget"); }
@Override public DBCursor findEvents( DBCollection collection, String aggregateIdentifier, long firstSequenceNumber) { return collection .find(CommitEntry.forAggregate(aggregateIdentifier, firstSequenceNumber)) .sort(new BasicDBObject(CommitEntry.SEQUENCE_NUMBER_PROPERTY, ORDER_ASC)); }
/** * 上午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; }
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(); } }
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(); }
@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 JsonArray updatePerfResults(String perfResults) { BasicDBObject doc = (BasicDBObject) JSON.parse(perfResults); doc.append("_id", doc.get("name")); DBCollection coll = db.getCollection("performance"); BasicDBObject query = new BasicDBObject(); query.put("_id", doc.get("name")); DBCursor cursor = coll.find(query); JsonObjectBuilder objBuild = Json.createObjectBuilder(); JsonArrayBuilder arrBuild = Json.createArrayBuilder(); JsonObject json = objBuild.build(); if (cursor.count() > 0) { LOG.info("Performance Results Found and Updated: " + coll.update(query, doc, true, false)); json = Json.createReader(new StringReader(perfResults)).readObject(); return arrBuild.add(json).build(); } else { LOG.info("Performance Results Created: " + coll.insert(doc)); json = Json.createReader(new StringReader(perfResults)).readObject(); return arrBuild.add(json).build(); } }
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(); } }