List of usage examples for com.mongodb AggregationOptions builder
public static Builder builder()
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Get the positions of the model links at the given timestamp * save result in MongoDB/*from ww w . jav a 2 s . com*/ */ public void WriteLinksPositionsAt(String ts_str, String model_name, String traj_db_name) { // transform the knowrob time to double with 3 decimal precision double timestamp = (double) Math.round((parseTime_d(ts_str) - TIME_OFFSET) * 1000) / 1000; // set default coll name String traj_coll_name = this.coll.getName();// + "_" + model_name + "_links_at_"+ timestamp; // remove the knowrob namespace (http://knowrob.org/kb/knowrob.owl#) form the model // String model_name = kr_model_name.split("#")[1]; //System.out.println("Java - timestamp: " + timestamp + " model name: " + model_name); // $and list for querying the $match in the aggregation BasicDBList time_and_name = new BasicDBList(); // add the timestamp and the model name time_and_name.add(new BasicDBObject("timestamp", new BasicDBObject("$lte", timestamp))); time_and_name.add(new BasicDBObject("models.name", model_name)); // create the pipeline operations, first the $match DBObject match_time_and_name = new BasicDBObject("$match", new BasicDBObject("$and", time_and_name)); // sort the results in descending order on the timestamp (keep most recent result first) DBObject sort_desc = new BasicDBObject("$sort", new BasicDBObject("timestamp", -1)); // $limit the result to 1, we only need one pose DBObject limit_result = new BasicDBObject("$limit", 1); // $unwind models in order to output only the queried model DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("links_pos", "$models.links.pos"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time_and_name, sort_desc, limit_result, unwind_models, match_model, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); try { MongoClient mongoClient = new MongoClient(this.dbHost, 27017); DB traj_db = mongoClient.getDB(traj_db_name); // check if the collection already exists if (traj_db.collectionExists(traj_coll_name)) { System.out .println("!!! Collection: \'" + traj_db_name + "." + traj_coll_name + "\' already exists!"); } // create the collection else { // create collection DBCollection traj_coll = traj_db.getCollection(traj_coll_name); System.out.println("Java - Writing to \'" + traj_db_name + "." + traj_coll_name + "\'"); // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // get pancake roundess again in order to append it to the metadata double roundess = this.GetPancakeRoundness(ts_str, model_name); // create metadata doc BasicDBObject meta_data = new BasicDBObject("name", traj_coll_name).append("type", "links_pos") .append("timestamp", timestamp).append("roundness", roundess) .append("description", "Pancake links positions.."); // get the first document as the next cursor and append the metadata to it BasicDBObject first_doc = (BasicDBObject) cursor.next(); first_doc.append("metadata", meta_data); // insert document with metadata traj_coll.insert(first_doc); } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { System.out.println("Java - WriteLinksPositionsAt Query returned no results!'"); } // insert rest of trajectory while (cursor.hasNext()) { traj_coll.insert(cursor.next()); } } } catch (UnknownHostException e) { e.printStackTrace(); } }
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Get the positions of the model links at the given timestamp * view results as rviz markers//w w w.j a va2 s . c o m */ public void ViewLinksPositionsAt(String ts_str, String model_name, String markerID, String markerType, String color, float scale) { // transform the knowrob time to double with 3 decimal precision double timestamp = (double) Math.round((parseTime_d(ts_str) - TIME_OFFSET) * 1000) / 1000; // $and list for querying the $match in the aggregation BasicDBList time_and_name = new BasicDBList(); // add the timestamp and the model name time_and_name.add(new BasicDBObject("timestamp", new BasicDBObject("$lte", timestamp))); time_and_name.add(new BasicDBObject("models.name", model_name)); // create the pipeline operations, first the $match DBObject match_time_and_name = new BasicDBObject("$match", new BasicDBObject("$and", time_and_name)); // sort the results in descending order on the timestamp (keep most recent result first) DBObject sort_desc = new BasicDBObject("$sort", new BasicDBObject("timestamp", -1)); // $limit the result to 1, we only need one pose DBObject limit_result = new BasicDBObject("$limit", 1); // $unwind models in order to output only the queried model DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("links_pos", "$models.links.pos"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time_and_name, sort_desc, limit_result, unwind_models, match_model, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); // Traj as dynamic array ArrayList<Vector3d> positions = new ArrayList<Vector3d>(); // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // get the first document as the next cursor BasicDBObject first_doc = (BasicDBObject) cursor.next(); // get the list of links pos BasicDBList pos_list = (BasicDBList) first_doc.get("links_pos"); // pos_list and rot_list length should be always the same for (int i = 0; i < pos_list.size(); ++i) { positions.add(new Vector3d(((BasicDBObject) pos_list.get(i)).getDouble("x"), ((BasicDBObject) pos_list.get(i)).getDouble("y"), ((BasicDBObject) pos_list.get(i)).getDouble("z"))); } } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { System.out.println("Java - ViewLinksPositionsAt Query returned no results!'"); } // create the markers this.CreateMarkers(positions, markerID, markerType, color, scale); }
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Get the positions of the model links at the given timestamp * save result in MongoDB/* www. j a v a2 s . co m*/ */ public void WriteLinksTrajs(String start_str, String end_str, String model_name, String traj_db_name) { // transform the knowrob time to double with 3 decimal precision double start_ts = (double) Math.round((parseTime_d(start_str) - TIME_OFFSET) * 1000) / 1000; double end_ts = (double) Math.round((parseTime_d(end_str) - TIME_OFFSET) * 1000) / 1000; // set default coll name String traj_coll_name = this.coll.getName();/* + "_" + model_name + "_links_trajs_" + start_ts + "_" + end_ts;*/ // remove the knowrob namespace (http://knowrob.org/kb/knowrob.owl#) form the model // String model_name = kr_model_name.split("#")[1]; // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind models in order to output only the queried model DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("links_pos", "$models.links.pos"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_models, match_model, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); try { MongoClient mongoClient = new MongoClient(this.dbHost, 27017); DB traj_db = mongoClient.getDB(traj_db_name); // check if the collection already exists if (traj_db.collectionExists(traj_coll_name)) { System.out .println("!!! Collection: \'" + traj_db_name + "." + traj_coll_name + "\' already exists!"); } // create the collection else { // create collection DBCollection traj_coll = traj_db.getCollection(traj_coll_name); System.out.println("Java - Writing to \'" + traj_db_name + "." + traj_coll_name + "\'"); // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // create metadata doc BasicDBObject meta_data = new BasicDBObject("name", traj_coll_name) .append("type", "links_trajs").append("start", start_ts).append("end", end_ts) .append("description", "Pancake links trajectories.."); // get the first document as the next cursor and append the metadata to it BasicDBObject first_doc = (BasicDBObject) cursor.next(); first_doc.append("metadata", meta_data); // insert document with metadata traj_coll.insert(first_doc); } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { System.out.println("Java - WriteLinksPositionsAt Query returned no results!'"); } // insert rest of trajectory while (cursor.hasNext()) { traj_coll.insert(cursor.next()); } } } catch (UnknownHostException e) { e.printStackTrace(); } }
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Get the positions of the model links at the given timestamp * view as rviz markers/*from w w w . j av a 2 s . com*/ */ public void ViewLinksTrajs(String start_str, String end_str, String model_name, String markerID) { // transform the knowrob time to double with 3 decimal precision double start_ts = (double) Math.round((parseTime_d(start_str) - TIME_OFFSET) * 1000) / 1000; double end_ts = (double) Math.round((parseTime_d(end_str) - TIME_OFFSET) * 1000) / 1000; // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind models in order to output only the queried model DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("links_pos", "$models.links.pos"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_models, match_model, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); // Traj as dynamic array ArrayList<Vector3d> trajs = new ArrayList<Vector3d>(); // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // get the first document as the next cursor BasicDBObject first_doc = (BasicDBObject) cursor.next(); // get the list of links pos BasicDBList pos_list = (BasicDBList) first_doc.get("links_pos"); // pos_list and rot_list length should be always the same for (int i = 0; i < pos_list.size(); ++i) { trajs.add(new Vector3d(((BasicDBObject) pos_list.get(i)).getDouble("x"), ((BasicDBObject) pos_list.get(i)).getDouble("y"), ((BasicDBObject) pos_list.get(i)).getDouble("z"))); } } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { this.ViewLinksPositionsAt(start_str, model_name, markerID); } // insert rest of trajectory while (cursor.hasNext()) { // get the current document BasicDBObject curr_doc = (BasicDBObject) cursor.next(); // get the list of links pos BasicDBList pos_list = (BasicDBList) curr_doc.get("links_pos"); // pos_list and rot_list length should be always the same for (int i = 0; i < pos_list.size(); ++i) { trajs.add(new Vector3d(((BasicDBObject) pos_list.get(i)).getDouble("x"), ((BasicDBObject) pos_list.get(i)).getDouble("y"), ((BasicDBObject) pos_list.get(i)).getDouble("z"))); } } // create the markers this.CreateMarkers(trajs, markerID); }
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Get the positions of the model links at the given timestamp * view as rviz markers// w ww .j a v a 2 s.co m */ public void ViewLinksTrajs(String start_str, String end_str, String model_name, String markerID, String markerType, String color, float scale, double deltaT) { // transform the knowrob time to double with 3 decimal precision double start_ts = (double) Math.round((parseTime_d(start_str) - TIME_OFFSET) * 1000) / 1000; double end_ts = (double) Math.round((parseTime_d(end_str) - TIME_OFFSET) * 1000) / 1000; // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind models in order to output only the queried model DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("links_pos", "$models.links.pos"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_models, match_model, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); // Traj as dynamic array ArrayList<Vector3d> trajs = new ArrayList<Vector3d>(); double prev_ts = 0; // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // get the first document as the next cursor BasicDBObject first_doc = (BasicDBObject) cursor.next(); // get the list of links pos BasicDBList pos_list = (BasicDBList) first_doc.get("links_pos"); // get the timestamp prev_ts = first_doc.getDouble("timestamp"); // pos_list and rot_list length should be always the same for (int i = 0; i < pos_list.size(); ++i) { trajs.add(new Vector3d(((BasicDBObject) pos_list.get(i)).getDouble("x"), ((BasicDBObject) pos_list.get(i)).getDouble("y"), ((BasicDBObject) pos_list.get(i)).getDouble("z"))); } } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { this.ViewLinksPositionsAt(start_str, model_name, markerID, markerType, color, scale); } // insert rest of trajectory while (cursor.hasNext()) { // get the current document BasicDBObject curr_doc = (BasicDBObject) cursor.next(); // get the list of links pos BasicDBList pos_list = (BasicDBList) curr_doc.get("links_pos"); double curr_ts = curr_doc.getDouble("timestamp"); // if time diff > then deltaT add position to trajectory if (curr_ts - prev_ts > deltaT) { // pos_list and rot_list length should be always the same for (int i = 0; i < pos_list.size(); ++i) { trajs.add(new Vector3d(((BasicDBObject) pos_list.get(i)).getDouble("x"), ((BasicDBObject) pos_list.get(i)).getDouble("y"), ((BasicDBObject) pos_list.get(i)).getDouble("z"))); } prev_ts = curr_ts; } } // create the markers this.CreateMarkers(trajs, markerID, markerType, color, scale); }
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Get the positions of the model links at the given timestamp *//*from ww w . j av a2s. c o m*/ public List<Point3d> GetLinksPositions(String ts_str, String model_name) { // list of all the links positions List<Point3d> links_positions = new ArrayList<Point3d>(); // transform the knowrob time to double with 3 decimal precision double timestamp = (double) Math.round((parseTime_d(ts_str) - TIME_OFFSET) * 1000) / 1000; // remove the knowrob namespace (http://knowrob.org/kb/knowrob.owl#) form the model // String model_name = kr_model_name.split("#")[1]; //System.out.println("Java - timestamp: " + timestamp + " model name: " + model_name); // $and list for querying the $match in the aggregation BasicDBList time_and_name = new BasicDBList(); // add the timestamp and the model name time_and_name.add(new BasicDBObject("timestamp", new BasicDBObject("$lte", timestamp))); time_and_name.add(new BasicDBObject("models.name", model_name)); // create the pipeline operations, first the $match DBObject match_time_and_name = new BasicDBObject("$match", new BasicDBObject("$and", time_and_name)); // sort the results in descending order on the timestamp (keep most recent result first) DBObject sort_desc = new BasicDBObject("$sort", new BasicDBObject("timestamp", -1)); // $limit the result to 1, we only need one pose DBObject limit_result = new BasicDBObject("$limit", 1); // $unwind models in order to output only the queried model DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("links_pos", "$models.links.pos"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time_and_name, sort_desc, limit_result, unwind_models, match_model, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); // if query has a response, append metadata to it if (cursor.hasNext()) { // get the first doc BasicDBObject first_doc = (BasicDBObject) cursor.next(); // get the positions array BasicDBList links_pos_arr = (BasicDBList) first_doc.get("links_pos"); // iterate the results for (int i = 0; i < links_pos_arr.size(); i++) { // current position Point3d pos = new Point3d(); // set the positions pos.x = ((BasicDBObject) links_pos_arr.get(i)).getDouble("x"); pos.y = ((BasicDBObject) links_pos_arr.get(i)).getDouble("y"); pos.z = ((BasicDBObject) links_pos_arr.get(i)).getDouble("z"); // add position to the list links_positions.add(pos); } } return links_positions; }
From source file:org.lucee.mongodb.DBCollectionImpl.java
License:Open Source License
@Override public Object call(PageContext pc, Key methodName, Object[] args) throws PageException { // aggregate/*w w w. j a v a 2 s . c om*/ if (methodName.equals("aggregate")) { boolean hasOptions = false; AggregationOptions options = null; int len = checkArgLength("aggregate", args, 1, -1); // no length limitation List<DBObject> pipeline = new ArrayList<DBObject>(); // Pipeline array as single argument if (len == 1 && decision.isArray(args[0])) { Array arr = caster.toArray(args[0]); if (arr.size() == 0) throw exp.createApplicationException( "the array passed to the function aggregate needs at least 1 element"); Iterator<Object> it = arr.valueIterator(); while (it.hasNext()) { pipeline.add(toDBObject(it.next())); } } else { // First argument is pipeline of operations, second argument is struct of options --> returns cursor! if (len == 2 && decision.isArray(args[0]) && decision.isStruct(args[1])) { Array arr = caster.toArray(args[0]); Iterator<Object> it = arr.valueIterator(); while (it.hasNext()) { pipeline.add(toDBObject(it.next())); } hasOptions = true; // options builder AggregationOptions.Builder optbuilder = AggregationOptions.builder() .outputMode(AggregationOptions.OutputMode.CURSOR); DBObject dboOpts = toDBObject(args[1]); if (dboOpts.containsField("allowDiskUse")) { if (!decision.isBoolean(dboOpts.get("allowDiskUse"))) throw exp.createApplicationException("allowDiskUse in options must be boolean value"); optbuilder = optbuilder.allowDiskUse(caster.toBooleanValue(dboOpts.get("allowDiskUse"))); } if (dboOpts.containsField("cursor")) { if (!decision.isStruct(dboOpts.get("cursor"))) throw exp.createApplicationException( "cursor in options must be struct with optional key batchSize"); DBObject cursoropts = toDBObject(dboOpts.get("cursor")); if (cursoropts.containsField("batchSize")) { if (!decision.isNumeric(cursoropts.get("batchSize"))) throw exp.createApplicationException("cursor.batchSize in options must be integer"); optbuilder = optbuilder.batchSize(caster.toIntValue(cursoropts.get("batchSize"))); } } options = optbuilder.build(); } // First argument is first operation, second argument is array of additional operations else if (len == 2 && decision.isArray(args[1])) { Array arr = caster.toArray(args[1]); pipeline.add(toDBObject(args[0])); Iterator<Object> it = arr.valueIterator(); while (it.hasNext()) { pipeline.add(toDBObject(it.next())); } } // N arguments of pipeline operations else { for (int i = 0; i < len; i++) { pipeline.add(toDBObject(args[i])); } } } if (hasOptions) { // returns Cursor - requires >= MongoDB 2.6 return toCFML(coll.aggregate(pipeline, options)); } else { // returns AggregationOutput return toCFML(coll.aggregate(pipeline)); } } // count if (methodName.equals("count")) { int len = checkArgLength("count", args, 0, 1); if (len == 0) { return toCFML(coll.count()); } else if (len == 1) { return toCFML(coll.count(toDBObject(args[0]))); } } // dataSize if (methodName.equals("dataSize")) { checkArgLength("dataSize", args, 0, 0); return toCFML(coll.getStats().get("size")); } // distinct if (methodName.equals("distinct")) { int len = checkArgLength("distinct", args, 1, 2); if (len == 1) { return toCFML(coll.distinct(caster.toString(args[0]))); } else if (len == 2) { return toCFML(coll.distinct(caster.toString(args[0]), toDBObject(args[1]))); } } // drop if (methodName.equals("drop")) { checkArgLength("drop", args, 0, 0); coll.drop(); return null; } // dropIndex if (methodName.equals("dropIndex")) { checkArgLength("dropIndex", args, 1, 1); DBObject dbo = toDBObject(args[0], null); if (dbo != null) coll.dropIndex(dbo); else coll.dropIndex(caster.toString(args[0])); return null; } // dropIndexes if (methodName.equals("dropIndexes")) { int len = checkArgLength("dropIndexes", args, 0, 1); if (len == 0) { coll.dropIndexes(); return null; } else if (len == 1) { coll.dropIndexes(caster.toString(args[0])); return null; } } // createIndex if (methodName.equals("createIndex") || methodName.equals("ensureIndex")) { int len = checkArgLength("createIndex", args, 1, 3); if (len == 1) { DBObject dbo = toDBObject(args[0], null); if (dbo != null) coll.createIndex(dbo); else coll.createIndex(caster.toString(args[0])); return null; } if (len == 2) { DBObject p1 = toDBObject(args[0]); DBObject p2 = toDBObject(args[1], null); if (p2 != null) coll.createIndex(p1, p2); else coll.createIndex(p1, caster.toString(args[1])); return null; } else if (len == 3) { coll.createIndex(toDBObject(args[0]), caster.toString(args[1]), caster.toBooleanValue(args[2])); return null; } } // getStats if (methodName.equals("getStats") || methodName.equals("stats")) { checkArgLength("getStats", args, 0, 0); return toCFML(coll.getStats()); } // getIndexes if (methodName.equals("getIndexes") || methodName.equals("getIndexInfo")) { checkArgLength(methodName.getString(), args, 0, 0); return toCFML(coll.getIndexInfo()); } // getWriteConcern if (methodName.equals("getWriteConcern")) { checkArgLength("getWriteConcern", args, 0, 0); return toCFML(coll.getWriteConcern()); } // find if (methodName.equals("find")) { int len = checkArgLength("find", args, 0, 3); DBCursor cursor = null; if (len == 0) { cursor = coll.find(); } else if (len == 1) { cursor = coll.find(toDBObject(args[0])); } else if (len == 2) { cursor = coll.find(toDBObject(args[0]), toDBObject(args[1])); } else if (len == 3) { cursor = coll.find(toDBObject(args[0]), toDBObject(args[1])).skip(caster.toIntValue(args[2])); } return toCFML(cursor); } // findOne else if (methodName.equals("findOne")) { int len = checkArgLength("findOne", args, 0, 3); DBObject obj = null; if (len == 0) { obj = coll.findOne(); } else if (len == 1) { DBObject arg1 = toDBObject(args[0], null); if (arg1 != null) obj = coll.findOne(arg1); else obj = coll.findOne(args[0]); } else if (len == 2) { DBObject arg1 = toDBObject(args[0], null); if (arg1 != null) obj = coll.findOne(arg1, toDBObject(args[1])); else obj = coll.findOne(args[0], toDBObject(args[1])); } else if (len == 3) { obj = coll.findOne(toDBObject(args[0]), toDBObject(args[1]), toDBObject(args[2])); } return toCFML(obj); } // findAndRemove if (methodName.equals("findAndRemove")) { checkArgLength("findAndRemove", args, 1, 1); DBObject obj = coll.findAndRemove(toDBObject(args[0])); return toCFML(obj); } // findAndModify if (methodName.equals("findAndModify")) { int len = args == null ? 0 : args.length; if (len != 2 && len != 3 && len != 7) { throw exp.createApplicationException( "the function findAndModify needs 2, 3 or 7 arguments, but you have defined only " + len); } DBObject obj = null; if (len == 2) { obj = coll.findAndModify(toDBObject(args[0]), toDBObject(args[1])); } else if (len == 3) { obj = coll.findAndModify(toDBObject(args[0]), toDBObject(args[1]), toDBObject(args[2])); } else if (len == 7) { obj = coll.findAndModify(toDBObject(args[0]), toDBObject(args[1]), toDBObject(args[2]), caster.toBooleanValue(args[3]), toDBObject(args[4]), caster.toBooleanValue(args[5]), caster.toBooleanValue(args[6])); } return toCFML(obj); } //group /* TODO: needs GroupCommand if(methodName.equals("group")) { int len=checkArgLength("group",args,1,1); if(len==1){ return toCFML(coll.group( toDBObject(args[0]) )); } }*/ // insert if (methodName.equals("insert")) { checkArgLength("insert", args, 1, 1); return toCFML(coll.insert(toDBObjectArray(args[0]))); } // insertMany(required array documents, struct options) valid options keys are string "writeconcern", boolean "ordered" if (methodName.equals("insertMany")) { int len = checkArgLength("insertMany", args, 1, 2); BulkWriteOperation bulk = coll.initializeOrderedBulkOperation(); WriteConcern wc = coll.getWriteConcern(); if (len == 2) { DBObject dboOpts = toDBObject(args[1]); if (dboOpts.containsField("ordered")) { if (!decision.isBoolean(dboOpts.get("ordered"))) throw exp.createApplicationException("ordered in options must be boolean value"); if (!caster.toBooleanValue(dboOpts.get("ordered"))) { bulk = coll.initializeUnorderedBulkOperation(); } } if (dboOpts.containsField("writeconcern")) { WriteConcern newWc = WriteConcern.valueOf(caster.toString(dboOpts.get("writeconcern"))); if (newWc != null) { wc = newWc; } } } Map<String, Object> result = new LinkedHashMap<String, Object>(); BulkWriteResult bulkResult; List<Map> writeErrors = new ArrayList<Map>(); Array arr = caster.toArray(args[0]); if (arr.size() == 0) { result.put("nInserted", 0); result.put("writeErrors", writeErrors); result.put("acknowledged", true); return toCFML(result); } Iterator<Object> it = arr.valueIterator(); while (it.hasNext()) { bulk.insert(toDBObject(it.next())); } try { bulkResult = bulk.execute(wc); } catch (BulkWriteException e) { Map<String, Object> bulkErrorItem; BulkWriteError bulkError; bulkResult = e.getWriteResult(); List<BulkWriteError> errors = e.getWriteErrors(); Iterator<BulkWriteError> jj = errors.iterator(); while (jj.hasNext()) { bulkErrorItem = new LinkedHashMap<String, Object>(); bulkError = jj.next(); bulkErrorItem.put("index", (bulkError.getIndex() + 1)); // +1 so we get index of item in CFML array bulkErrorItem.put("code", bulkError.getCode()); bulkErrorItem.put("errmsg", bulkError.getMessage()); bulkErrorItem.put("op", bulkError.getDetails()); writeErrors.add(bulkErrorItem); } } result.put("acknowledged", bulkResult.isAcknowledged()); if (bulkResult.isAcknowledged()) { result.put("nInserted", bulkResult.getInsertedCount()); result.put("writeErrors", writeErrors); } return toCFML(result); } // bulkWrite(required array operations, struct options) valid options keys are string "writeconcern", boolean "ordered", boolean "bypassDocumentValidation" // an operation is a struct with the following keys: { "operation":[insert|update|updateOne|remove|removeOne], "document":[(required if operation is insert) - a doc to insert], "query":[(optional) - the query to find for remove/update operations], "update":[(required for update/updateOne) - the update document] } // i.e. dbCollection.bulkWrite([ // {"operation":"insert", "document":{"test":"insert"}} // ,{"operation":"updateOne", "query":{"_id":"foo"}, "update":{"$set":{"updated":true}}} // ,{"operation":"removeOne", "query":{"_id":"goaway"}} // ],{"ordered":false}) if (methodName.equals("bulkWrite")) { int len = checkArgLength("bulkWrite", args, 1, 2); BulkWriteOperation bulk = coll.initializeOrderedBulkOperation(); WriteConcern wc = coll.getWriteConcern(); if (len == 2) { DBObject dboOpts = toDBObject(args[1]); if (dboOpts.containsField("ordered")) { if (!decision.isBoolean(dboOpts.get("ordered"))) throw exp.createApplicationException("ordered in options must be boolean value"); if (!caster.toBooleanValue(dboOpts.get("ordered"))) { bulk = coll.initializeUnorderedBulkOperation(); } } if (dboOpts.containsField("bypassDocumentValidation")) { if (!decision.isBoolean(dboOpts.get("bypassDocumentValidation"))) throw exp.createApplicationException( "bypassDocumentValidation in options must be boolean value"); bulk.setBypassDocumentValidation( caster.toBooleanValue(dboOpts.get("bypassDocumentValidation"))); } if (dboOpts.containsField("writeconcern")) { WriteConcern newWc = WriteConcern.valueOf(caster.toString(dboOpts.get("writeconcern"))); if (newWc != null) { wc = newWc; } } } Map<String, Object> result = new LinkedHashMap<String, Object>(); BulkWriteResult bulkResult; List<Map> writeErrors = new ArrayList<Map>(); Array arr = caster.toArray(args[0]); if (arr.size() == 0) { result.put("nInserted", 0); result.put("nMatched", 0); result.put("nModified", 0); result.put("nRemoved", 0); result.put("writeErrors", writeErrors); result.put("acknowledged", true); return toCFML(result); } Iterator<Object> it = arr.valueIterator(); while (it.hasNext()) { DBObject operation = toDBObject(it.next()); if (operation.get("operation") == "update") { // do stuff to add update operation bulk.find(toDBObject(operation.get("query"))).update(toDBObject(operation.get("update"))); } else if (operation.get("operation") == "updateOne") { // do stuff to add updateOne operation bulk.find(toDBObject(operation.get("query"))).updateOne(toDBObject(operation.get("update"))); } else if (operation.get("operation") == "remove") { // do stuff to add remove operation bulk.find(toDBObject(operation.get("query"))).remove(); } else if (operation.get("operation") == "removeOne") { // do stuff to add removeOne operation bulk.find(toDBObject(operation.get("query"))).removeOne(); } else if (operation.get("operation") == "insert") { bulk.insert(toDBObject(operation.get("document"))); } } try { bulkResult = bulk.execute(wc); } catch (BulkWriteException e) { Map<String, Object> bulkErrorItem; BulkWriteError bulkError; bulkResult = e.getWriteResult(); List<BulkWriteError> errors = e.getWriteErrors(); Iterator<BulkWriteError> jj = errors.iterator(); while (jj.hasNext()) { bulkErrorItem = new LinkedHashMap<String, Object>(); bulkError = jj.next(); bulkErrorItem.put("index", (bulkError.getIndex() + 1)); // +1 so we get index of item in CFML array bulkErrorItem.put("code", bulkError.getCode()); bulkErrorItem.put("errmsg", bulkError.getMessage()); bulkErrorItem.put("op", bulkError.getDetails()); writeErrors.add(bulkErrorItem); } } result.put("acknowledged", bulkResult.isAcknowledged()); if (bulkResult.isAcknowledged()) { result.put("nInserted", bulkResult.getInsertedCount()); result.put("nMatched", bulkResult.getMatchedCount()); result.put("nModified", bulkResult.getModifiedCount()); result.put("nRemoved", bulkResult.getRemovedCount()); result.put("writeErrors", writeErrors); } return toCFML(result); } //mapReduce if (methodName.equals("mapReduce")) { int len = checkArgLength("mapReduce", args, 4, 4); if (len == 4) { return toCFML(coll.mapReduce(caster.toString(args[0]), caster.toString(args[1]), caster.toString(args[2]), toDBObject(args[3]))); } } // remove if (methodName.equals("remove")) { checkArgLength("remove", args, 1, 1); return toCFML(coll.remove(toDBObject(args[0]))); } // rename if (methodName.equals("rename") || methodName.equals("renameCollection")) { int len = checkArgLength(methodName.getString(), args, 1, 2); if (len == 1) { return toCFML(coll.rename(caster.toString(args[0]))); } else if (len == 2) { return toCFML(coll.rename(caster.toString(args[0]), caster.toBooleanValue(args[1]))); } } // save if (methodName.equals("save")) { checkArgLength("save", args, 1, 1); return toCFML(coll.save(toDBObject(args[0]))); } // setWriteConcern if (methodName.equals("setWriteConcern")) { checkArgLength("setWriteConcern", args, 1, 1); WriteConcern wc = WriteConcern.valueOf(caster.toString(args[0])); if (wc != null) { coll.setWriteConcern(wc); } return null; } // storageSize if (methodName.equals("storageSize")) { checkArgLength("storageSize", args, 0, 0); return toCFML(coll.getStats().get("storageSize")); } // totalIndexSize if (methodName.equals("totalIndexSize")) { checkArgLength("totalIndexSize", args, 0, 0); return toCFML(coll.getStats().get("totalIndexSize")); } // update if (methodName.equals("update")) { int len = checkArgLength("update", args, 2, 4); if (len == 2) { return toCFML(coll.update(toDBObject(args[0]), toDBObject(args[1]))); } else if (len == 3) { return toCFML(coll.update(toDBObject(args[0]), toDBObject(args[1]), caster.toBooleanValue(args[2]), false)); } else if (len == 4) { return toCFML(coll.update(toDBObject(args[0]), toDBObject(args[1]), caster.toBooleanValue(args[2]), caster.toBooleanValue(args[3]))); } } String functionNames = "aggregate,count,dataSize,distinct,drop,dropIndex,dropIndexes,createIndex,stats,getIndexes,getWriteConcern,find,findOne,findAndRemove,findAndModify," + "group,insert,insertMany,bulkWrite,mapReduce,remove,rename,save,setWriteConcern,storageSize,totalIndexSize,update"; throw exp.createApplicationException( "function " + methodName + " does not exist existing functions are [" + functionNames + "]"); }
From source file:org.teiid.translator.mongodb.MongoDBExecutionFactory.java
License:Open Source License
public AggregationOptions getOptions(int batchSize) { if (this.version.equals(TWO_6)) { return AggregationOptions.builder().batchSize(batchSize) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(useDisk()).build(); }// w w w .j av a 2 s .c o m return AggregationOptions.builder().batchSize(batchSize).outputMode(AggregationOptions.OutputMode.INLINE) .build(); }