用java連線mongodb並執行$match和$group結合的聚合函式的例項。

suyu_yuan發表於2016-07-07

1、測試類:

package test;
/** 
* @author : suyuyuan
* @date :2016年6月23日 下午3:10:03 
* @version 1.0 
*/


import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;


public class MongoMatch {


public static void main(String[] args) {
DBCollection collection;
try {
// 獲取連線
collection = MongoUtil.getCollection();
// 查詢資料
List<DBObject> ops = new ArrayList<DBObject>();
DBObject query = new BasicDBObject();
query.put("status", "A");
DBObject match = new BasicDBObject("$match", query);
ops.add(match);
DBObject group = new BasicDBObject("$group", new BasicDBObject("_id","$cust_id").append("total", new BasicDBObject("$sum","$amount")));
ops.add(group);
AggregationOutput output = collection.aggregate(ops);
Iterable<DBObject> iterable = output.results();
Iterator<DBObject> iterator = iterable.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
//以上輸出方式也可以用以下方式替代更為正規:

// Cursor cursor = collection.aggregate(ops, AggregationOptions.builder().allowDiskUse(true).build());
// while(cursor.hasNext()) {
// DBObject doc = cursor.next();
// System.out.println(doc);
// }

} catch (UnknownHostException e) {
e.printStackTrace();
}
}


}


2、工具類:

package test;


import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;


/**
 * @author : suyuyuan
 * @date :2016年6月24日 上午10:36:28
 * @version 1.0
 */
public class MongoUtil {


private static String dbIp = "localhost";
private static int dbPort = 27017;
private static String mydb = "mongotest";
private static String table = "orders";


public static DBCollection getCollection() throws UnknownHostException {


// // 例項化Mongo物件,
// Mongo mongo = new Mongo(dbIp, dbPort);
// // 連線名為yourdb的資料庫,假如資料庫不存在的話,mongodb會自動建立
// DB db = mongo.getDB(dbUser);
// // 從Mongodb中獲得名為myData的資料集合,如果該資料集合不存在,Mongodb會為其新建立
// DBCollection collection = db.getCollection(table);


MongoClient mongoClient = new MongoClient(new ServerAddress(dbIp, dbPort));
DB db = mongoClient.getDB(mydb);
DBCollection collection = db.getCollection(table);


return collection;
}


}


3、maven的pom依賴:


<dependency>
<groupId>org.mongodb.morphia</groupId>
<artifactId>morphia</artifactId>
<version>1.2.0</version>
</dependency>


<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>


4、對應的NoSql如下:

db.orders.aggregate(
 [
  {$match:{status:"A"}},
  {$group:{_id:"$cust_id",total:{$sum:"$amount"}}}
 ]
 )





相關文章