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

原理:合集处理——笛卡尔迭代器实现,逐个遍历元素,形成一个笛卡尔集合。
参考: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);
}
}

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

3、结果如下

数据集合的大小为:4*4*4*4*4=1024;
这里写图片描述
这里写图片描述

2017-04-27
作者:铭毅天下
转载请标明出处,原文地址:
http://blog.csdn.net/laoyang360/article/details/70946468
如果感觉本文对您有帮助,请点击‘顶’支持一下,您的支持是我坚持写作最大的动力,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

铭毅天下

和你一起,死磕Elastic!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值