List of usage examples for com.mongodb DBCollection findOne
@Nullable
public DBObject findOne()
From source file:example.QuickTour.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes no args/* www .j a v a 2s . c om*/ * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017 */ public static void main(final String[] args) throws UnknownHostException { // connect to the local database server MongoClient mongoClient = new MongoClient(); // get handle to "mydb" DB db = mongoClient.getDB("mydb"); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); // get a list of the collections in this database and print them out Set<String> collectionNames = db.getCollectionNames(); for (final String s : collectionNames) { System.out.println(s); } // get a collection object to work with DBCollection testCollection = db.getCollection("testCollection"); // drop all the data in it testCollection.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1) .append("info", new BasicDBObject("x", 203).append("y", 102)); testCollection.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = testCollection.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { testCollection.insert(new BasicDBObject().append("i", i)); } System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + testCollection.getCount()); // lets get all the documents in the collection and print them out DBCursor cursor = testCollection.find(); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject("i", 71); cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // now use a range query to get a larger subset query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // range query with multiple constraints query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cursor = testCollection.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // create an index on the "i" field testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = testCollection.getIndexInfo(); for (final DBObject o : list) { System.out.println(o); } // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); // see if any previous operation had an error System.out.println("Previous error : " + db.getPreviousError()); // force an error db.forceError(); // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); db.resetError(); // release resources mongoClient.close(); }
From source file:examples.QuickTour.java
License:Apache License
public static void main(String[] args) throws Exception { // connect to the local database server Mongo m = new Mongo(); // get handle to "mydb" DB db = m.getDB("mydb"); // Authenticate - optional boolean auth = db.authenticate("foo", new char[] { 'b', 'a', 'r' }); // get a list of the collections in this database and print them out Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s);/* ww w . j a v a2 s . co m*/ } // get a collection object to work with DBCollection coll = db.getCollection("testCollection"); // drop all the data in it coll.drop(); // make a document and insert it BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc); // get it (since it's the only one in there since we dropped the rest earlier on) DBObject myDoc = coll.findOne(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors for (int i = 0; i < 100; i++) { coll.insert(new BasicDBObject().append("i", i)); } System.out .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount()); // lets get all the documents in the collection and print them out DBCursor cur = coll.find(); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a query to get 1 document out BasicDBObject query = new BasicDBObject(); query.put("i", 71); cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // now use a range query to get a larger subset query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // range query with multiple contstraings query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cur = coll.find(query); while (cur.hasNext()) { System.out.println(cur.next()); } // create an index on the "i" field coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending // list the indexes on the collection List<DBObject> list = coll.getIndexInfo(); for (DBObject o : list) { System.out.println(o); } // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); // see if any previous operation had an error System.out.println("Previous error : " + db.getPreviousError()); // force an error db.forceError(); // See if the last operation had an error System.out.println("Last error : " + db.getLastError()); db.resetError(); }
From source file:fr.cirad.web.controller.gigwa.base.AbstractVariantController.java
License:Open Source License
/** * List variants.//w w w .j ava 2 s .c om * * @param request the request * @param sModule the module * @param projId the proj id * @param selectedVariantTypes the selected variant types * @param selectedSequences the selected sequences * @param selectedIndividuals the selected individuals * @param gtPattern the gt code * @param genotypeQualityThreshold the genotype quality threshold * @param readDepthThreshold the read depth threshold * @param missingData the missing data * @param minmaf the minmaf * @param maxmaf the maxmaf * @param minposition the minposition * @param maxposition the maxposition * @param alleleCount the allele count * @param geneName the gene name * @param variantEffects the variant effects * @param wantedFields the wanted fields * @param page the page * @param size the size * @param sortBy the sort by * @param sortDir the sort dir * @param processID the process id * @return the array list * @throws Exception the exception */ @RequestMapping(variantListURL) /** * This method returns a list of variants from the current selection */ protected @ResponseBody ArrayList<Comparable[]> listVariants(HttpServletRequest request, @RequestParam("module") String sModule, @RequestParam("project") int projId, @RequestParam("variantTypes") String selectedVariantTypes, @RequestParam("sequences") String selectedSequences, @RequestParam("individuals") String selectedIndividuals, @RequestParam("gtPattern") String gtPattern, @RequestParam("genotypeQualityThreshold") int genotypeQualityThreshold, @RequestParam("readDepthThreshold") int readDepthThreshold, @RequestParam("missingData") double missingData, @RequestParam("minmaf") Float minmaf, @RequestParam("maxmaf") Float maxmaf, @RequestParam("minposition") Long minposition, @RequestParam("maxposition") Long maxposition, @RequestParam("alleleCount") String alleleCount, @RequestParam("geneName") String geneName, @RequestParam("variantEffects") String variantEffects, @RequestParam("wantedFields") String wantedFields, @RequestParam("page") int page, @RequestParam("size") int size, @RequestParam("sortBy") String sortBy, @RequestParam("sortDir") String sortDir, @RequestParam("processID") String processID) throws Exception { String[] usedFields = wantedFields.split(";"); String token = processID.substring(1 + processID.indexOf('|')); String queryKey = getQueryKey(request, sModule, projId, selectedVariantTypes, selectedSequences, selectedIndividuals, gtPattern, genotypeQualityThreshold, readDepthThreshold, missingData, minmaf, maxmaf, minposition, maxposition, alleleCount, geneName, variantEffects); MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule); DBCollection cachedCountcollection = mongoTemplate.getCollection(MgdbDao.COLLECTION_NAME_CACHED_COUNTS); // cachedCountcollection.drop(); DBCursor countCursor = cachedCountcollection.find(new BasicDBObject("_id", queryKey)); Object[] partialCountArray = !countCursor.hasNext() ? null : ((BasicDBList) countCursor.next().get(MgdbDao.FIELD_NAME_CACHED_COUNT_VALUE)).toArray(); HashMap<Integer, String> variantFieldMap = new HashMap<Integer, String>(), runDataFieldMap = new HashMap<Integer, String>(); for (int i = 0; i < usedFields.length; i++) if (usedFields[i].startsWith("#")) variantFieldMap.put(i, usedFields[i].substring(1)); else runDataFieldMap.put(i, usedFields[i]); long expectedCount = 0; for (Object aPartialCount : partialCountArray) expectedCount += (Long) aPartialCount; DBCollection tmpVarCollOrView = getTemporaryVariantCollection(sModule, token, false); boolean fGotTempData = tmpVarCollOrView.findOne() != null; ArrayList<Comparable[]> result = new ArrayList<Comparable[]>(); DBCollection variantColl = mongoTemplate.getCollection(mongoTemplate.getCollectionName(VariantData.class)); if (fGotTempData || expectedCount == variantColl.count()) // otherwise we return an empty list because there seems to be a problem (missing temp records) { boolean fProjectHasAnnotations = getProjectEffectAnnotations(sModule, projId).size() > 0; DBCollection varCollForBuildingRows = fGotTempData ? tmpVarCollOrView : variantColl; DBCursor variantsInFilterCursor = varCollForBuildingRows.find(); ArrayList<Object[]> variantRows = buildVariantRows(mongoTemplate, variantsInFilterCursor, sortBy, sortDir, page, size, variantFieldMap, runDataFieldMap); for (Object[] aRow : variantRows) { List<Comparable> anOutputRow = new ArrayList<Comparable>(); for (int i = 0; i < aRow.length; i++) { String val = null; if (!usedFields[i].startsWith(VariantRunData.SECTION_ADDITIONAL_INFO + ".")) val = aRow[i] == null ? "" : aRow[i].toString(); else if (aRow[i] != null && fProjectHasAnnotations) val = aRow[i].toString().replaceAll("[\\[\\]\"]", ""); // it's an annotation field: make its content look cleaner if (val != null) anOutputRow.add(val); } anOutputRow.add(anOutputRow.get(0)); // for details link result.add(anOutputRow.toArray(new Comparable[anOutputRow.size()])); } } if (fGotTempData && page == 0 && tmpVarCollOrView.getIndexInfo().size() <= 1) new Thread() { // temp data needs to be indexed for faster browsing public void run() { long b4 = System.currentTimeMillis(); tmpVarCollOrView.createIndex(VariantData.FIELDNAME_VERSION); tmpVarCollOrView.createIndex( VariantData.FIELDNAME_REFERENCE_POSITION + "." + ReferencePosition.FIELDNAME_SEQUENCE); tmpVarCollOrView.createIndex(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ReferencePosition.FIELDNAME_START_SITE); tmpVarCollOrView.createIndex(VariantData.FIELDNAME_TYPE); LOG.debug("Indexing " + tmpVarCollOrView.count() + " temp variants took " + (System.currentTimeMillis() - b4) / 1000f + "s"); } }.start(); return result; }
From source file:fr.cnes.sitools.datasource.mongodb.business.SitoolsMongoDBDataSource.java
License:Open Source License
/** * Get the list of fields of a collection * //ww w . j a va2 s .c om * @param collectionName * the name of the mongoDB collection * @return name of related columns of the table TODO evolution return List<Column> */ // TODO public List<String> getMetadata(String collectionName) { List<String> columnNameList = null; DB mongoDatabase = null; mongoDatabase = getDatabase(); columnNameList = new ArrayList<String>(); DBCollection collection = mongoDatabase.getCollection(collectionName); DBObject dbObject = collection.findOne(); columnNameList.addAll(dbObject.keySet()); return columnNameList; }
From source file:fr.cnes.sitools.datasource.mongodb.dbexplorer.MongoDBExplorerResource.java
License:Open Source License
/** * Process constraint//from www. ja v a 2s. c o m * * @param variant * Client preference * @return Representation to be used */ public Representation processConstraint(Variant variant) { Representation represent = null; SitoolsMongoDBDataSource datasource = getDataSource(); DB database = datasource.getDatabase(); // DATABASE TARGET if (this.databaseTarget) { CommandResult cmd = database.getStats(); List<String> messages = new ArrayList<String>(); traceObjects(cmd, messages); Response response = new Response(true, messages, String.class, "statusInfo"); represent = getRepresentation(response, variant); } // COLLECTIONS TARGET => GET THE LIST OF COLLECTIONS if (this.collectionsTarget) { Database mongoDatabase = getCollections(database); Response response = new Response(true, mongoDatabase, Database.class, "mongodbdatabase"); return getRepresentation(response, variant); } // COLLECTION TARGET => GET THE DESCRIPTION OF THE COLLECTION if (this.collectionTarget) { Collection collection = getACollection(database, this.collectionName); Response response = new Response(true, collection, Collection.class, "collection"); return getRepresentation(response, variant); } if (this.recordSetTarget) { DBCollection collectionMongo = database.getCollection(this.collectionName); this.start = getPaginationStartRecord(); this.limit = getPaginationExtend(); limit = (limit > maxrows) ? maxrows : limit; if (limit == 0) { limit = maxrows; } DBCursor cursor = collectionMongo.find().skip(start).limit(limit); // cursor.setOptions(Bytes.QUERYOPTION_EXHAUST); return new MongoDBExplorerRepresentation(getMediaType(variant), cursor, this); } // TODO a marche pas trop if (this.recordTarget) { DBCollection collectionMongo = database.getCollection(this.collectionName); DBObject query = new BasicDBObject(); if (ObjectId.isValid(this.idDocument)) { query.put("_id", new ObjectId(this.idDocument)); } else { query.put("_id", this.idDocument); } DBCursor cursor = collectionMongo.find(query).limit(1); this.setStart(0); this.setLimit(1); return new MongoDBExplorerRepresentation(getMediaType(variant), cursor, this); } if (this.metadataTarget) { DBCollection collectionMongo = database.getCollection(this.collectionName); BasicDBObject object = (BasicDBObject) collectionMongo.findOne(); List<MongoDBAttributeValue> values = null; if (object != null && !object.isEmpty()) { values = getAttributeValue(object, false); } Response response = new Response(true, values, MongoDBAttributeValue.class, "fields"); return getRepresentation(response, variant); } return represent; }
From source file:govt_import_export.Order.java
private void sort_cars() { MongoClient mongo = null;//from w w w.ja v a 2 s. com try { mongo = new MongoClient("localhost", 27017); //get database } catch (UnknownHostException | MongoException e) { } String[] st = new String[10]; st[0] = "HYUNDAI"; st[1] = "MARUTISUZUKI"; st[2] = "NISSAN"; st[3] = "BAJAJ"; st[4] = "KTM"; st[5] = "VOLKSVAGEN"; DB db = mongo.getDB("AUTOMOBILEXPO"); DBCollection table; ArrayList<Order> arr = new ArrayList<Order>(); for (int j = 0; j < 6; j++) { table = db.getCollection(st[j]); if (table.findOne() != null) { String map = "function () {" + "emit(this.model,this.Units);" + "}"; String reduce; reduce = "function (key,value) { " + "return Array.sum(value)}"; MapReduceCommand cmd = new MapReduceCommand(table, map, reduce, null, MapReduceCommand.OutputType.INLINE, null); MapReduceOutput out = table.mapReduce(cmd); String str; for (DBObject o : out.results()) { str = o.get("value").toString().trim(); System.out.println(str); int i = 0; // var i=(int)(Convert.ToDouble("1.2")); //int a = int.Parse("1.2".Split('.')[0]); if (!str.equals(null)) { Float f = Float.parseFloat(str); i = (int) Math.ceil(f); arr.add(new Order(o.get("_id").toString(), i) { @Override public int compare(Order o1, Order o2) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public int compareTo(Order o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); } } } } Collections.sort(arr, new Order() { }); for (Order a : arr) System.out.println(" " + a.getid() + " " + a.getval()); this.dispose(); Sorted s = new Sorted(arr); s.setVisible(true); }
From source file:govt_import_export.display_2.java
private void disp(String s) { MongoClient mongo = null;//from w w w . j a v a 2 s . co m int x = 0; try { mongo = new MongoClient("localhost", 27017); } catch (UnknownHostException | MongoException e) { } if (jTable1.getRowCount() > 0) { for (int i = jTable1.getRowCount() - 1; i > -1; i--) { model.removeRow(i); } } DB db = mongo.getDB("AUTOMOBILEXPO"); String[] st = new String[10]; st[0] = "HYUNDAI"; st[1] = "MARUTISUZUKI"; st[2] = "NISSAN"; st[3] = "BAJAJ"; st[4] = "KTM"; st[5] = "VOLKSVAGEN"; String s1, s2, s3; s1 = jComboBox1.getSelectedItem().toString(); s2 = jComboBox2.getSelectedItem().toString(); s3 = jComboBox3.getSelectedItem().toString(); BasicDBObject search = new BasicDBObject(); BasicDBObject result = new BasicDBObject(); BasicDBObject sp = new BasicDBObject(); if (s.equals(s1)) { int i = Integer.parseInt(s); sp.put("Year", i); if (jCheckBox2.isSelected() && jCheckBox3.isSelected()) { sp.append("country", s2); sp.append("manufacturer", s3); } else if (jCheckBox2.isSelected()) { sp.append("country", s2); } else if (jCheckBox3.isSelected()) { sp.append("manufacturer", s3); } } else if (s.equals(s2)) { sp.put("country", s2); int i = Integer.parseInt(s1); if (jCheckBox1.isSelected() && jCheckBox3.isSelected()) { sp.append("Year", i); //sp.append("country",s2); sp.append("manufacturer", s3); } else if (jCheckBox1.isSelected()) { //sp.append("country",s2); sp.append("Year", i); } else if (jCheckBox3.isSelected()) { sp.append("manufacturer", s3); } } else if (s.equals(s3)) { sp.put("manufacturer", s3); int i = Integer.parseInt(s1); if (jCheckBox1.isSelected() && jCheckBox2.isSelected()) { sp.append("Year", i); sp.append("country", s2); //sp.append("manufacturer",s3); } else if (jCheckBox1.isSelected()) { //sp.append("country",s2); sp.append("Year", i); } else if (jCheckBox2.isSelected()) { sp.append("country", s2); } } ArrayList<String> arr = new ArrayList(); for (int j = 0; j <= 5; j++) { DBCollection table; table = db.getCollection(st[j]); if (table.findOne() != null) { DBCursor cr = table.find(sp); DBObject obj; while (cr.hasNext()) { obj = cr.next(); x++; //jLabel1.setText(jLabel1.getText()+"Model\n"+(obj.toString())+"\n"); //jTextArea1. // jTextArea1.setText(jTextArea1.getText()+"Manufacture: "+(obj.get("manufacturer").toString())+" Model: "+(obj.get("model").toString())+" Units : "+(obj.get("Units").toString())+"Cost : "+(obj.get("Cost").toString())+" Continent : "+(obj.get("country").toString())+" Year :"+(obj.get("Year").toString())+"\n"); model.addRow(new Object[] { obj.get("manufacturer").toString(), (obj.get("model").toString()), (obj.get("Units").toString()), (obj.get("Cost").toString()), (obj.get("country").toString()), (obj.get("Year").toString()) }); } } } total = x; String a = Integer.toString(total); jLabel5.setText(a); }
From source file:govt_import_export.display_2.java
private void simple_display() { MongoClient mongo = null;//w ww . ja v a2 s.c o m try { mongo = new MongoClient("localhost", 27017); } catch (UnknownHostException | MongoException e) { } // String batches=(String)jComboBox1.getSelectedItem( ); //get collections if (jTable1.getRowCount() > 0) { for (int i = jTable1.getRowCount() - 1; i > -1; i--) { model.removeRow(i); } } int x = 0; DB db = mongo.getDB("AUTOMOBILEXPO"); String[] st = new String[10]; st[0] = "HYUNDAI"; st[1] = "MARUTISUZUKI"; st[2] = "NISSAN"; st[3] = "BAJAJ"; st[4] = "KTM"; st[5] = "VOLKSVAGEN"; ArrayList<String> arr = new ArrayList(); for (int j = 0; j <= 5; j++) { DBCollection table; table = db.getCollection(st[j]); if (table.findOne() != null) { BasicDBObject search = new BasicDBObject(); BasicDBObject result = new BasicDBObject(); BasicDBObject sp = new BasicDBObject(); DBCursor cr = table.find(); //System.out.println(table.findOne()); String str; DBObject obj; while (cr.hasNext()) { x++; obj = cr.next(); //jTextArea1.setText(jTextArea1.getText()+" Manufacture : "+(obj.get("manufacturer").toString())+" Model : "+(obj.get("model").toString())+" Units : "+(obj.get("Units").toString())+" Cost : "+(obj.get("Cost").toString())+" Continent : "+(obj.get("country").toString())+" Year : "+(obj.get("Year").toString())+"\n"); model.addRow(new Object[] { obj.get("manufacturer").toString(), (obj.get("model").toString()), (obj.get("Units").toString()), (obj.get("Cost").toString()), (obj.get("country").toString()), (obj.get("Year").toString()) }); } } } total = x; String a = Integer.toString(total); jLabel5.setText(a); }
From source file:mongodb.findDocument.java
public static void getOne(DBCollection collection) { DBObject doc = collection.findOne(); System.out.println("Single Document: "); System.out.println(doc.toString()); }
From source file:mongodb.MongoDBOperations.java
License:Apache License
public void printOne(DBCollection coll) { DBObject myDoc = coll.findOne(); //System.out.println(myDoc); }