groovy 访问 MongoDB 示例:
shell.groovy
package dbimport com.gmongo.GMongoClientimport com.mongodb.BasicDBObjectimport com.mongodb.MongoCredentialimport com.mongodb.ServerAddress/** * 本地无密 mongodb 数据库连接 */def connect() { GMongoClient client = new GMongoClient(new ServerAddress('127.0.0.1',50513)) return client}/** * SSH mongodb 数据库连接 */def connectSSH() { //以下这两行是针对包含用户名和密码配置的数据库的。 MongoCredential credentials = MongoCredential.createMongoCRCredential('root','xy', 'pass' as char[]) //MongoClientOptions options = MongoClientOptions.builder().connectTimeout(1000) //创建一个Client连接,如果是认证的则使用下面的这一行 GMongoClient client = new GMongoClient(new ServerAddress('10.101.114.108',22), [credentials]) return client}def topics(map) { def DB = connect().getDB('xy') /*def sl = map['$gte'] def el = map['$lte']*/ //查询条件 BasicDBObject object = new BasicDBObject('timestamp',new BasicDBObject(map)) println(object.toString()) println(DB.getCollection('topics').count(object)) //println(DB.getCollection('topics').count())}def topic_tip(map) { def DB = connect().getDB('xy') //查询条件 BasicDBObject object1 = new BasicDBObject('$match',new BasicDBObject(map)) BasicDBObject object2 = new BasicDBObject('$group',new BasicDBObject('_id',null).append('num_tutorial',new BasicDBObject('$sum','$kd_money'))) //聚合查询 //db.getCollection('topic_tip').aggregate([{$match:{ 'timestamp' : { '$gte' : 1376065109781 , '$lte' : 1576065109781}}},{$group : {_id : null, num_tutorial : {$sum : '$kd_money'}}}]) println(DB.getCollection('topic_tip').aggregate(object1,object2))}def currency_log(map) { def DB = connect().getDB('xy') //查询条件 BasicDBObject object1 = new BasicDBObject('$match',new BasicDBObject(map)) BasicDBObject object2 = new BasicDBObject('$group',new BasicDBObject('_id',null).append('num_tutorial',new BasicDBObject('$sum','$kd_money'))) //聚合查询 //db.getCollection('currency_log').aggregate([{$match:{ "currency_time" : { "$gte" : 1504368000000 , "$lte" : 1504454399000}}},{$group : {_id : "$currency_type", num_tutorial : {$sum : "$currency_money"}}}]) println(DB.getCollection('currency_log').aggregate(object1,object2))}
java 调用 shell.groovy 文件
package test;import groovy.lang.GroovyClassLoader;import groovy.lang.GroovyObject;import javafx.application.Application;import javafx.stage.Stage;import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;public class Shell extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { try { GroovyClassLoader loader = new GroovyClassLoader(); Class groovyClass = loader.parseClass(new File(Shell.class.getClassLoader().getResource("db/shell.groovy").getPath())); GroovyObject object = (GroovyObject) groovyClass.newInstance(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String[] timeStart = new String[]{"2017-08-28 00:00:00","2017-08-29 00:00:00","2017-08-30 00:00:00","2017-08-31 00:00:00"}; String[] timeEnd = new String[]{"2017-08-28 23:59:59","2017-08-29 23:59:59","2017-08-30 23:59:59","2017-08-31 23:59:59"}; for (int i=0 ;i<7; i++) { Date start = format.parse(timeStart[i]); Date end = format.parse(timeEnd[i]); Mapparams = new HashMap<>(); params.put("$gte",start.getTime()); params.put("$lte",end.getTime()); // topics 是 shell.groovy 中的方法名,params 是传给 topics 的参数,执行下面语句完成 topics 方法脚本的调用 object.invokeMethod("topics",params); } /*GroovyScriptEngine engine = new GroovyScriptEngine(Shell.class.getClassLoader().getResource("db").getPath()); Binding binding = new Binding(); binding.setVariable("language","Groovy"); engine.run("studenttopicdata.groovy",binding);*/ } catch (Exception e) { e.printStackTrace(); System.out.println("Exception e = " + e.toString()); } }}