List of usage examples for com.mongodb AggregationOutput results
List results
To view the source code for com.mongodb AggregationOutput results.
Click Source Link
From source file:es.bsc.amon.controller.EventsDBMapper.java
License:Open Source License
public BasicDBList aggregate(BasicDBObject dbo) { List<DBObject> query = new ArrayList<DBObject>(1); query.add(dbo);//from ww w . j a v a 2 s . c o m AggregationOutput aggOut = colEvents.aggregate(query); BasicDBList dbl = new BasicDBList(); Iterator<DBObject> it = aggOut.results().iterator(); while (it.hasNext()) { dbl.add(it.next()); } return dbl; }
From source file:es.bsc.amon.controller.EventsDBMapper.java
License:Open Source License
public BasicDBList aggregate(BasicDBList query) { List<DBObject> ql = new ArrayList<DBObject>(query.size()); Iterator<Object> itq = query.iterator(); while (itq.hasNext()) ql.add((DBObject) itq.next());/*from w ww.j a va2 s . c om*/ AggregationOutput aggOut = colEvents.aggregate(ql); BasicDBList dbl = new BasicDBList(); Iterator<DBObject> it = aggOut.results().iterator(); while (it.hasNext()) { dbl.add(it.next()); } return dbl; }
From source file:example.AggregationExample.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes no args//w w w. j a va 2 s.c o m * @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"); // Add some sample data DBCollection coll = db.getCollection("aggregationExample"); coll.insert(new BasicDBObjectBuilder().add("employee", 1).add("department", "Sales").add("amount", 71) .add("type", "airfare").get()); coll.insert(new BasicDBObjectBuilder().add("employee", 2).add("department", "Engineering").add("amount", 15) .add("type", "airfare").get()); coll.insert(new BasicDBObjectBuilder().add("employee", 4).add("department", "Human Resources") .add("amount", 5).add("type", "airfare").get()); coll.insert(new BasicDBObjectBuilder().add("employee", 42).add("department", "Sales").add("amount", 77) .add("type", "airfare").get()); // create our pipeline operations, first with the $match DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "airfare")); // build the $projection operation DBObject fields = new BasicDBObject("department", 1); fields.put("amount", 1); fields.put("_id", 0); DBObject project = new BasicDBObject("$project", fields); // Now the $group operation DBObject groupFields = new BasicDBObject("_id", "$department"); groupFields.put("average", new BasicDBObject("$avg", "$amount")); DBObject group = new BasicDBObject("$group", groupFields); // Finally the $sort operation DBObject sort = new BasicDBObject("$sort", new BasicDBObject("average", -1)); // run aggregation List<DBObject> pipeline = Arrays.asList(match, project, group, sort); AggregationOutput output = coll.aggregate(pipeline); // Output the results for (DBObject result : output.results()) { System.out.println(result); } // Aggregation Cursor AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = coll.aggregate(pipeline, aggregationOptions); while (cursor.hasNext()) { System.out.println(cursor.next()); } // clean up db.dropDatabase(); mongoClient.close(); }
From source file:fr.ensimag.biblio.dao.impl.MongoDBUserDAO.java
public Map<String, Double> getUsersBirthTownStatistics() { // *** Count total number of users : DBObject totalGroupFields = new BasicDBObject("_id", "$town"); // we use the $sum operator to increment the "count" // for each unique town totalGroupFields.put("count", new BasicDBObject("$sum", 1)); DBObject totalGroup = new BasicDBObject("$group", totalGroupFields); AggregationOutput totalOutput = col.aggregate(totalGroup); int total = Integer.parseInt(String.valueOf(totalOutput.results().iterator().next().get("count"))); Map<String, Double> stats = new HashMap<String, Double>(); // *** Count number of users for each town : DBObject groupFields = new BasicDBObject("_id", "$town"); // we use the $sum operator to increment the "count" // for each unique town groupFields.put("count", new BasicDBObject("$sum", 1)); DBObject group = new BasicDBObject("$group", groupFields); // You can add a sort to order by count descending DBObject sortFields = new BasicDBObject("count", -1); DBObject sort = new BasicDBObject("$sort", sortFields); AggregationOutput output = col.aggregate(group, sort); for (DBObject result : output.results()) { String town = (String) result.get("_id"); Double count = Double.parseDouble(String.valueOf(result.get("count"))) / total; stats.put(town, count);/* w w w .ja v a2s.co m*/ //System.out.println(stats.get(town)); } return stats; }
From source file:GeoHazardServices.Inst.java
License:Apache License
private DBObject getUserObj(String username) { DBCollection coll = db.getCollection("users"); DBCursor cursor = coll.find(new BasicDBObject("username", username)); if (!cursor.hasNext()) return null; DBObject obj = cursor.next();//from w ww .j a va 2 s.c o m cursor.close(); BasicDBObject userObj = new BasicDBObject("username", obj.get("username")); userObj.put("_id", obj.get("_id")); userObj.put("permissions", obj.get("permissions")); userObj.put("properties", obj.get("properties")); userObj.put("notify", obj.get("notify")); userObj.put("api", obj.get("api")); ObjectId instId = (ObjectId) obj.get("inst"); cursor = db.getCollection("institutions").find(new BasicDBObject("_id", instId)); String instName = null; if (cursor.hasNext()) { DBObject inst = cursor.next(); inst.removeField("_id"); inst.removeField("secret"); userObj.put("inst", inst); instName = (String) inst.get("name"); } cursor.close(); if (instName == null || instName.equals("gfz") || instName.equals("tdss15")) instName = "gfz_ex_test"; /* get all available country codes and count elements in each group */ DBObject groupFields = new BasicDBObject("_id", "$country"); groupFields.put("count", new BasicDBObject("$sum", 1)); DBObject group = new BasicDBObject("$group", groupFields); BasicDBList types = new BasicDBList(); types.add(new BasicDBObject("sensor", "rad")); types.add(new BasicDBObject("sensor", "prs")); types.add(new BasicDBObject("sensor", "pr1")); types.add(new BasicDBObject("sensor", "flt")); types.add(new BasicDBObject("sensor", null)); DBObject filterFields = new BasicDBObject("$or", types); BasicDBList andList = new BasicDBList(); andList.add(filterFields); andList.add(new BasicDBObject("inst", instName)); DBObject andObj = new BasicDBObject("$and", andList); DBObject filter = new BasicDBObject("$match", andObj); /* sort alphabetically */ DBObject sortFields = new BasicDBObject("_id", 1); DBObject sort = new BasicDBObject("$sort", sortFields); AggregationOutput output = db.getCollection("stations").aggregate(filter, group, sort); BasicDBList countries = new BasicDBList(); /* convert answer into string list */ @SuppressWarnings("unchecked") List<String> clist = (List<String>) obj.get("countries"); for (DBObject res : output.results()) { String code = (String) res.get("_id"); if (code == null) continue; boolean isOn = (clist != null) && clist.contains(code); res.put("on", isOn); countries.add(res); } userObj.put("countries", countries); return userObj; }
From source file:io.liveoak.mongo.MongoAggregationResource.java
License:Open Source License
private BasicDBList aggregate(RequestContext ctx) { BasicDBList queryObject = new BasicDBList(); if (ctx.resourceParams() != null && ctx.resourceParams().contains("q")) { String queryString = ctx.resourceParams().value("q"); DBObject paramObject = (DBObject) JSON.parse(queryString); if (paramObject instanceof BasicDBList) { queryObject = (BasicDBList) paramObject; } else {/* w w w . ja v a2s. com*/ queryObject.add(paramObject); } } DBCollection dbCollection = parent().getDBCollection(); try { BasicDBList result = new BasicDBList(); AggregationOutput output = dbCollection.aggregate((DBObject) queryObject.remove(0), queryObject.toArray(new DBObject[queryObject.size()])); for (DBObject dbObject : output.results()) { result.add(dbObject); } return result; } catch (Exception e) { logger().error("", e); throw new RuntimeException("Aggregation query failed: ", e); } }
From source file:MDBInt.DBMongo.java
License:Apache License
private Iterable<DBObject> operate(String dbName, String collectionName, String campoMatch, String valoreMatch, String campoOperazione, String nomeOperazione, String operation) { DB database = this.getDB(dbName); DBCollection collezione;//from w w w. j av a 2 s. c om DBObject match, fields, project, groupFields, group, sort; AggregationOutput output; Iterable<DBObject> cursor; List<DBObject> pipeline; collezione = database.getCollection(collectionName); match = new BasicDBObject("$match", new BasicDBObject(campoMatch, valoreMatch)); fields = new BasicDBObject(campoOperazione, 1); fields.put("_id", 0); project = new BasicDBObject("$project", fields); groupFields = new BasicDBObject("_id", campoOperazione); groupFields.put(nomeOperazione, new BasicDBObject(operation, "$" + campoOperazione)); group = new BasicDBObject("$group", groupFields); sort = new BasicDBObject("$sort", new BasicDBObject(campoOperazione, -1)); pipeline = Arrays.asList(match, project, group, sort); output = collezione.aggregate(pipeline); cursor = output.results(); return cursor; }
From source file:mongodb.JavaAggregate.java
public static void displayAggregate(AggregationOutput result) { for (Iterator<DBObject> items = result.results().iterator(); items.hasNext();) { System.out.println(items.next()); }/* w ww . j a v a 2 s.c o m*/ }
From source file:mongodb.tedc.Week1Homework4.java
License:Apache License
public static void main(String[] args) throws IOException { /* ------------------------------------------------------------------------ */ /* You should do this ONLY ONCE in the whole application life-cycle: */ /* Create and adjust the configuration singleton */ Configuration cfg = new Configuration(Configuration.VERSION_2_3_21); cfg.setDirectoryForTemplateLoading(new File("src/main/resources")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); MongoClient client = new MongoClient(new ServerAddress("localhost", 27017)); DB database = client.getDB("m101"); final DBCollection collection = database.getCollection("funnynumbers"); get("/", (req, res) -> { StringWriter writer = new StringWriter(); try {/*from ww w .ja v a 2 s . c om*/ // Not necessary yet to understand this. It's just to prove that you // are able to run a command on a mongod server DBObject groupFields = new BasicDBObject("_id", "$value"); groupFields.put("count", new BasicDBObject("$sum", 1)); DBObject group = new BasicDBObject("$group", groupFields); DBObject match = new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1)); // run aggregation List<DBObject> pipeline = Arrays.asList(group, match, sort); AggregationOutput output = collection.aggregate(pipeline); int answer = 0; for (DBObject doc : output.results()) { answer += (Double) doc.get("_id"); } /* Create a data-model */ Map<String, String> answerMap = new HashMap<>(); answerMap.put("answer", Integer.toString(answer)); /* Get the template (uses cache internally) */ Template helloTemplate = cfg.getTemplate("answer.ftl"); /* Merge data-model with template */ helloTemplate.process(answerMap, writer); } catch (Exception e) { logger.error("Failed", e); halt(500); } return writer; }); }
From source file:net.hydromatic.optiq.impl.mongodb.MongoTable.java
License:Apache License
/** Executes an "aggregate" operation on the underlying collection. * * <p>For example:/* ww w . j a v a2s.co m*/ * <code>zipsTable.aggregate( * "{$filter: {state: 'OR'}", * "{$group: {_id: '$city', c: {$sum: 1}, p: {$sum: '$pop'}}}") * </code></p> * * @param mongoDb MongoDB connection * @param fields List of fields to project; or null to return map * @param operations One or more JSON strings * @return Enumerator of results */ public Enumerable<Object> aggregate(final DB mongoDb, final List<String> fields, final List<String> operations) { List<DBObject> list = new ArrayList<DBObject>(); for (String operation : operations) { list.add((DBObject) JSON.parse(operation)); } final DBObject first = list.get(0); final List<DBObject> rest = Util.skip(list); final Function1<DBObject, Object> getter = MongoEnumerator.getter(fields); return new AbstractEnumerable<Object>() { public Enumerator<Object> enumerator() { final AggregationOutput result; try { result = mongoDb.getCollection(collectionName).aggregate(first, rest.toArray(new DBObject[rest.size()])); } catch (Exception e) { throw new RuntimeException( "While running MongoDB query " + Util.toString(operations, "[", ",\n", "]"), e); } return new MongoEnumerator(result.results().iterator(), getter); } }; }