List of usage examples for com.mongodb DBCollection find
public DBCursor find()
From source file:com.badger.observationmongotest.execute.Main.java
public static void main(String[] args) throws ParseException, UnknownHostException, IOException { List<Observation> observations = new LinkedList(); Customer customer = new Customer(); customer.setName("Mr Customer"); customer.setId("cid123"); customer.setBackOfficeId("boid123"); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); String dateStr = "2015/08/10"; Date date = format.parse(dateStr); CustomerObservationReport report = new CustomerObservationReport(customer); MonthlyProductOrderCountIssue productOrderCountIssue = new MonthlyProductOrderCountIssue(); productOrderCountIssue.setActionRequired(true); productOrderCountIssue.setCatagory("product issue"); productOrderCountIssue.setCurrentYear(2015); productOrderCountIssue.setCurrentYearValue(30); productOrderCountIssue.setCustomerId(customer.getId()); productOrderCountIssue.setDate(date); productOrderCountIssue.setDrop(50.0); productOrderCountIssue.setLastYearValue(60); productOrderCountIssue.setMonth("Feb"); productOrderCountIssue.setObservationId("oid123"); productOrderCountIssue.setPreviousYear(2014); productOrderCountIssue.setProductName("cool product"); productOrderCountIssue.setScore(4500); productOrderCountIssue.setType("monthy order count"); MonthlyProductOrderCountIssue monthlyProductOrderCountIssue = new MonthlyProductOrderCountIssue(); monthlyProductOrderCountIssue.setActionRequired(true); monthlyProductOrderCountIssue.setCatagory("product issue"); monthlyProductOrderCountIssue.setCurrentYear(2015); monthlyProductOrderCountIssue.setCurrentYearValue(30); monthlyProductOrderCountIssue.setCustomerId(customer.getId()); monthlyProductOrderCountIssue.setDate(date); monthlyProductOrderCountIssue.setDrop(50.0); monthlyProductOrderCountIssue.setLastYearValue(60); monthlyProductOrderCountIssue.setMonth("March"); monthlyProductOrderCountIssue.setObservationId("oid456"); monthlyProductOrderCountIssue.setPreviousYear(2014); monthlyProductOrderCountIssue.setProductName("cool product"); monthlyProductOrderCountIssue.setScore(4500); monthlyProductOrderCountIssue.setType("monthy order count"); MonthlyProductRevenueIssue monthlyProductRevenueIssue = new MonthlyProductRevenueIssue(); monthlyProductRevenueIssue.setActionRequired(true); monthlyProductRevenueIssue.setCatagory("product issue"); monthlyProductRevenueIssue.setCurrentYear(2015); monthlyProductRevenueIssue.setCurrentYearValue(3000.00); monthlyProductRevenueIssue.setCustomerId(customer.getId()); monthlyProductRevenueIssue.setDate(date); monthlyProductRevenueIssue.setDrop(50.0); monthlyProductRevenueIssue.setLastYearValue(6000.00); monthlyProductRevenueIssue.setMonth("Dec"); monthlyProductRevenueIssue.setObservationId("oid3445"); monthlyProductRevenueIssue.setPreviousYear(2014); monthlyProductRevenueIssue.setProductName("test product"); monthlyProductRevenueIssue.setScore(5667); monthlyProductRevenueIssue.setType("monthly product ervenue"); MonthlyRevenueIssue monthlyRevenueIssue = new MonthlyRevenueIssue(); monthlyRevenueIssue.setActionRequired(true); monthlyRevenueIssue.setCatagory("Reveue Issue"); monthlyRevenueIssue.setCurrentValue(3000); monthlyRevenueIssue.setCurrentYear(2015); monthlyRevenueIssue.setCustomerId(customer.getId()); monthlyRevenueIssue.setDate(date);//from w w w.j a v a 2s. c o m monthlyRevenueIssue.setDrop(45.0); monthlyRevenueIssue.setMonth("Nov"); monthlyRevenueIssue.setObservationId("oid4646646"); monthlyRevenueIssue.setPreviousValue(5000); monthlyRevenueIssue.setPreviousYear(2014); monthlyRevenueIssue.setScore(5600); monthlyRevenueIssue.setType("monthly revenue issue"); observations.add(monthlyRevenueIssue); observations.add(monthlyProductRevenueIssue); observations.add(monthlyProductOrderCountIssue); observations.add(productOrderCountIssue); report.setAccountId("acid123"); report.addObservations(observations); // BasicDBObject documentDetail = new BasicDBObject(); /** * documentDetail.put("accountId", report.getAccountId()); * documentDetail.put("customerId", report.getCustomerId()); * documentDetail.put("Observations", * report.getObservations().toString()); * */ MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("ObservationReports"); DBCollection col = db.getCollection("reports"); Gson gson = new Gson(); String json = gson.toJson(report); DBObject dbObject = (DBObject) JSON.parse(json); col.insert(dbObject); //DBObject query = BasicDBObjectBuilder.start().add("_id", report.getId()).get(); DBCursor cursor = col.find(); while (cursor.hasNext()) { System.out.println("First Cursor: " + cursor.next().get("observations")); } while (cursor.hasNext()) { DBObject dbobj = cursor.next(); Map map = dbObject.toMap(); CustomerObservationReport report2 = new CustomerObservationReport(customer); //System.out.println("observations " +dbObject.get("observations")); List<Observation> dbObservations = (List<Observation>) dbObject.get("observations"); report2.setAccountId(report.getAccountId()); report2.setCustomerId(report.getCustomerName()); report2.setBackOfficeId(report.getBackOfficeId()); report2.setObservations((dbObservations)); System.out.println(report2.getClass().getTypeName()); } }
From source file:com.bbc.remarc.ws.MetadataService.java
License:Apache License
/** * Core random find service for entities that have metadata * //from w w w .j a va2s. c o m * @param db * db instance * @param limit * number of records to find * @param filter * find records that match this filter. Can be null for no * filtering * @param collectionName * the database collection name * @return collection of found DBObjects */ protected List<DBObject> findRandom(DB db, long limit, DBObject filter, final String collectionName) { List<DBObject> results = new ArrayList<DBObject>(); try { db.requestStart(); Random random = new Random(); DBCollection dbCollection = db.getCollection(collectionName); long maxRecords = dbCollection.count(); if (limit > maxRecords) { limit = maxRecords; } for (int i = 0; i < limit; i++) { boolean foundUnique = false; int numChecked = 0; while (!foundUnique) { if (numChecked == limit) { break; } int randomNumber = random.nextInt((int) dbCollection.count()); DBObject randomRecord = null; if (filter == null) { randomRecord = dbCollection.find().limit(-1).skip(randomNumber).next(); } else { DBCursor cursor = dbCollection.find(filter).limit(-1); if (i >= cursor.count()) { // we dont have enough records from the filter to // match the limit break; } randomNumber = random.nextInt((int) cursor.count()); randomRecord = cursor.skip(randomNumber).next(); } foundUnique = resultsContains(randomRecord, results) == false; if (foundUnique) { randomRecord.removeField("_id"); results.add(randomRecord); } } } } finally { db.requestDone(); } return results; }
From source file:com.bbc.remarc.ws.ThemeServiceImpl.java
License:Apache License
@GET @Produces("application/json") public Response find() { List<DBObject> results = new ArrayList<DBObject>(); DB db = MongoClient.getDB();/* www . j ava 2s . c o m*/ db.requestStart(); DBCollection theme = db.getCollection(COLLECTION_NAME); DBCursor cursor = theme.find().limit(NUM_THEMES); if (cursor.length() != NUM_THEMES) { throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR) .entity("unexpected number of themes returned").build()); } results = cursor.toArray(); db.requestDone(); return Response.ok(String.format("%s", results)).build(); }
From source file:com.bosscs.spark.mongodb.extractor.MongoNativeExtractor.java
License:Apache License
/** * Gets shards.//from www . jav a 2s . c o m * * @param collection the collection * @return the shards */ private Map<String, String[]> getShards(DBCollection collection) { DB config = collection.getDB().getSisterDB("config"); DBCollection configShards = config.getCollection("shards"); DBCursor cursorShards = configShards.find(); Map<String, String[]> map = new HashMap<>(); while (cursorShards.hasNext()) { DBObject currentShard = cursorShards.next(); String currentHost = (String) currentShard.get("host"); int slashIndex = currentHost.indexOf("/"); if (slashIndex > 0) { map.put((String) currentShard.get(MONGO_DEFAULT_ID), currentHost.substring(slashIndex + 1).split(",")); } } return map; }
From source file:com.bugull.mongo.AdvancedDao.java
License:Apache License
private synchronized Iterable<DBObject> mapReduce(String map, String reduce, String outputTarget, MapReduceCommand.OutputType outputType, String orderBy, DBObject query) throws MapReduceException { MapReduceOutput output = coll.mapReduce(map, reduce, outputTarget, outputType, query); CommandResult cr = output.getCommandResult(); if (!cr.ok()) { throw new MapReduceException(cr.getErrorMessage()); }//w w w . j a va2 s. co m DBCollection c = output.getOutputCollection(); DBCursor cursor = null; if (orderBy != null) { cursor = c.find().sort(MapperUtil.getSort(orderBy)); } else { cursor = c.find(); } List<DBObject> list = new ArrayList<DBObject>(); for (Iterator<DBObject> it = cursor.iterator(); it.hasNext();) { list.add(it.next()); } return list; }
From source file:com.bugull.mongo.AdvancedDao.java
License:Apache License
private synchronized Iterable<DBObject> mapReduce(String map, String reduce, String outputTarget, MapReduceCommand.OutputType outputType, String orderBy, int pageNum, int pageSize, DBObject query) throws MapReduceException { MapReduceOutput output = coll.mapReduce(map, reduce, outputTarget, outputType, query); CommandResult cr = output.getCommandResult(); if (!cr.ok()) { throw new MapReduceException(cr.getErrorMessage()); }//from w w w . j ava2 s .com DBCollection c = output.getOutputCollection(); DBCursor cursor = null; if (orderBy != null) { cursor = c.find().sort(MapperUtil.getSort(orderBy)).skip((pageNum - 1) * pageSize).limit(pageSize); } else { cursor = c.find().skip((pageNum - 1) * pageSize).limit(pageSize); } List<DBObject> list = new ArrayList<DBObject>(); for (Iterator<DBObject> it = cursor.iterator(); it.hasNext();) { list.add(it.next()); } return list; }
From source file:com.callidusrobotics.droptables.model.DocumentDao.java
License:Open Source License
/** * Finds all documents./*from w w w . j a v a 2 s . c o m*/ * * @param collectionName * The collection to search * @return A list of matching documents, never null */ public List<DBObject> getAllDocuments(String collectionName) { DBCollection collection = getCollection(collectionName); DBCursor cursor = collection.find(); return getDocuments(cursor); }
From source file:com.chdi.kundenverwaltung.KundenVerwaltungsLogic.java
public List<Customer> findAllCustomer() { List<Customer> customers = new ArrayList<Customer>(); DBCollection table = db.getCollection("user"); DBCursor cursor = table.find(); while (cursor.hasNext()) { DBObject tobj = cursor.next();/* w w w . ja v a 2s. com*/ Customer tmp = new Customer((String) tobj.get("ID"), (String) tobj.get("CompanyName"), (String) tobj.get("Name"), (String) tobj.get("Adress")); customers.add(tmp); } return customers; }
From source file:com.cyslab.craftvm.rest.mongo.AggregateServlet.java
License:GNU General Public License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.trace("doGet()"); if (!can_read(req)) { res.sendError(SC_UNAUTHORIZED);/*w ww . j a va2 s . co m*/ return; } String db_name = req.getParameter("dbname"); String col_name = req.getParameter("colname"); 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"); DB db = mongo.getDB(db_name); DBCollection col = db.getCollection(col_name); DBCursor c = col.find(); if (c == null) { error(res, SC_NOT_FOUND, Status.get("no documents found")); return; } res.setIntHeader("X-Documents-Count", c.count()); if (limit != null) { try { c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN)); } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse limit")); c.close(); return; } } else c.limit(MAX_FIELDS_TO_RETURN); if (skip != null) { try { c.skip(Integer.parseInt(skip)); } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse skip")); c.close(); return; } } StringBuilder buf = tl.get(); buf.setLength(0); int no = 0; buf.append("["); while (c.hasNext()) { DBObject o = c.next(); JSON.serialize(o, buf); buf.append(","); no++; } if (no > 0) buf.setCharAt(buf.length() - 1, ']'); else buf.append(']'); res.setIntHeader("X-Documents-Returned", no); out_str(req, buf.toString(), "application/json"); }
From source file:com.cyslab.craftvm.rest.mongo.QueryServlet.java
License:GNU General Public License
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log.trace("doGet()"); if (!can_read(req)) { res.sendError(SC_UNAUTHORIZED);/*from ww w.j a v a 2s .com*/ return; } 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"); 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); DBCursor c = col.find(); if (c == null || c.count() == 0) { error(res, SC_NOT_FOUND, Status.get("no documents found")); return; } res.setIntHeader("X-Documents-Count", c.count()); if (limit != null) { try { c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN)); } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse limit")); c.close(); return; } } else c.limit(MAX_FIELDS_TO_RETURN); if (skip != null) { try { c.skip(Integer.parseInt(skip)); } catch (NumberFormatException e) { error(res, SC_BAD_REQUEST, Status.get("can not parse skip")); c.close(); return; } } StringBuilder buf = tl.get(); 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); out_str(req, buf.toString(), "application/json"); }