MongoDB 怎么计算子查询

 

关键词导读:Mongodb子查询 Mongodb关联查询

MongoDB在某些方面确实比关系型数据库更强 (比如对追加型日志数据的吞吐能力),但结构化计算能力方面较弱。比如:MongoDB不支持子查询,碰到这些复杂的运算就只能先将数据读出后再计算,而用Java等语言编写这类计算也不是很简单。

比如要处理这么个场景:查出订单信息,要求订单中的SELLERID必须是employee集合中STATE= California的员工id。如果写成sql就是:

Select * from orders where orders.sellerid in (select eid from employee where employee.state=California)

orders的数据量较大无法一次取出,employee的数据量较小,最终结果的数据量也较小。部分数据如下:

MongoDB Collection orders:

{ "_id" : ObjectId("5434f88dd00ab5276493e270"), "ORDERID" : 1, "CLIENT" : "UJRNP

","SELLERID" : 17, "AMOUNT" : 392, "ORDERDATE" : "2008/11/2 15:28" }

{ "_id" : ObjectId("5434f88dd00ab5276493e271"), "ORDERID" : 2, "CLIENT" : "SJCH"

, "SELLERID" : 6, "AMOUNT" : 4802, "ORDERDATE" : "2008/11/9 15:28" }

{ "_id" : ObjectId("5434f88dd00ab5276493e272"), "ORDERID" : 3, "CLIENT" : "UJRNP

","SELLERID" : 16, "AMOUNT" : 13500, "ORDERDATE" : "2008/11/5 15:28" }

{ "_id" : ObjectId("5434f88dd00ab5276493e273"), "ORDERID" : 4, "CLIENT" : "PWQ",

 "SELLERID" : 9, "AMOUNT" : 26100, "ORDERDATE" : "2008/11/8 15:28" }

MongoDB Collection employee:

{ "_id" : ObjectId("5437413513bdf2a4048f3480"), "EID" : 1, "NAME" : "Rebecca", "

SURNAME" : "Moore", "GENDER" : "F", "STATE" : "California", "BIRTHDAY" : "1974-1

1-20","HIREDATE" : "2005-03-11", "DEPT" : "R&D", "SALARY" : 7000 }

{ "_id" : ObjectId("5437413513bdf2a4048f3481"), "EID" : 2, "NAME" : "Ashley", "S

URNAME" : "Wilson", "GENDER" : "F", "STATE" : "New York", "BIRTHDAY" : "1980-07-

19","HIREDATE" : "2008-03-16", "DEPT" : "Finance", "SALARY" : 11000 }

{ "_id" : ObjectId("5437413513bdf2a4048f3482"), "EID" : 3, "NAME" : "Rachel", "S

URNAME" : "Johnson", "GENDER" : "F", "STATE" : "New Mexico", "BIRTHDAY" : "1970-

12-17","HIREDATE" : "2010-12-01", "DEPT" : "Sales", "SALARY" : 9000 }

计算结果:

如果有集算器的协助就简单多了,它是专门为结构化、半结构化数据计算设计的编程语言,查询、子查询、分组后过滤等等都有函数类库可以用,能够很好的弥补MongoDB在结构化方面计算能力的不足。比如上面问题,4行就搞定了:

 

A

1

=mongo_open("mongodb://localhost:27017/test?user=test&password=test")

2

=mongo_shell(A1,"orders.find(,{_id:0})")

3

=mongo_shell@x(A1,"employee.find({STATE:'California'},{_id:0})").fetch()

4

=A2.select(A3.(EID).sort().pos@b(SELLERID)).fetch()

其实还有很多情况用MongoDB处理结构化计算不太方便,但有集算器SPL的辅助却很简单,感兴趣可以参考:玩转Mongo计算简化MongoDB关联运算辅助MongoDB计算

集算器还很容易嵌入到Java应用程序中,Java如何调用SPL脚本有使用和获得它的方法。

关于集算器安装使用、获得免费授权和相关技术资料,可以参见如何使用集算器