天天看點

Mongo多個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);

1

2

3

4

5

6

7

8

9

10

11

12

輸出: CartesianIterable dkRst

CartesianIterable dkRst = CartesianIteratorTest.dk_process_obj(gatherList);

原理:合集處理——笛卡爾疊代器實作,逐個周遊元素,形成一個笛卡爾集合。

參考:

http://stackoverflow.com/questions/714108/cartesian-product-of-arbitrary-sets-in-java

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);

13

14

15

16

17

18

19

20

21

22

23

24

25

26

3、結果如下

資料集合的大小為:4*4*4*4*4=1024;

Mongo多個Collection的關聯操作實作
Mongo多個Collection的關聯操作實作