1. 程式人生 > >Mongo多個Collection的關聯操作實現

Mongo多個Collection的關聯操作實現

題記

在mysql,oracle等關係型資料庫中,可以通過表之間的關聯操作(join, left join, and)實現欄位之間的關聯操作。
而在mongo非關係型資料庫中沒有對應的介面。
為此,我們自身實現了1個Mongo db庫中的多個collection之間的類笛卡爾操作。(這種需求,多少有些不合理)

1、需求:Mongo多個Collection之間的關聯操作

輸入: gatherList,
組成如下:

List <Object> la = Arrays.asList (new Object [] {'A', 'B', 'C', 'D'}); //1
List <Object
> lb = Arrays.asList (new Object [] {1, 2, 3, 4}); //2 List <Object> lc = Arrays.asList (new Object [] {"百度", "小米", "谷歌", "Facebook"}); //3 List <Object> ld = Arrays.asList (new Object [] {"雷軍", "喬布斯", "羅永浩", "羅胖子"}); ///4 List <Object> le = Arrays.asList (new Object [] {"微博", "微信", "陌陌"
, "脈脈"}); //5 List <List <Object>> gatherList = new ArrayList <List <Object>> (); gatherList.add(la); gatherList.add(lb); gatherList.add(lc); gatherList.add(ld); gatherList.add(le);

輸出: CartesianIterable dkRst

CartesianIterable dkRst = CartesianIteratorTest.dk_process_obj(gatherList);

2、關聯結果入Mongodb。

void mongoInsertObj(CartesianIterable dkRst,
List labelNameList, int iGatherListSize)
輸入:1) CartesianIterable dkRst, 笛卡爾結果。
2) List labelNameList,列名稱集。
3) int iGatherListSize, 笛卡爾結果的組數,即 gatherList集的大小,等同於 列名稱集的大小。
輸出:空。
演算法實現:集合拆分——以 gatherList集的大小為一組,對應一個document入庫。
原始碼:

public static void mongoInsertObj(CartesianIterable<Object> dkRst,
List<String> labelNameList, int iGatherListSize)
throws UnknownHostException {
try {
/**** Connect to MongoDB ****/
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient("110.20.12.41", 27017);

/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("data");

/**** Get collection / table from 'testdb' ****/
DBCollection table = db.getCollection(testCollName);
for (List <Object> lo: dkRst){
int iObjSize = lo.size();
BasicDBObject document = new BasicDBObject();
for (int i = 0; i < iObjSize; i+=iGatherListSize) {
//System.out.println("NtnbRisk.labelNameList[0] = " + NtnbRisk.labelNameList[0]);
for (int j = 0; j < iGatherListSize; j++) {
// create a document to store key and value
document.put(labelNameList.get(j), lo.get(i+j)); //1
}
table.insert(document);
}
}

3、結果如下

資料集合的大小為:4*4*4*4*4=1024;
這裡寫圖片描述
這裡寫圖片描述