MongoDB的外键关联处理

   来源:http://stackoverflow.com/questions/29392169/populating-field-values-for-referred-documents-in-aggregate-call-in-mongoose

Mongodb本身的API需要硬编码才能实现外键关联,不够直观且难度较大,这种情况下可以用集算器来实现,下面用例子说明。

Collection UserCourseProgress记录着用户和课程的关系,其courseid字段是外键,指向Collection Course_id字段。需要统计出每门课的人数,其中课程名称需要使用Coursetitle字段。

UserCourseProgress

Course

{"userId":"u01",

"courseid":"c01",

"timespent":6000,

score:99}

{"userId":"u02",

"courseid":"c01",

"timespent":6000,

score:99}

{"userId":"u03",

"courseid":"c01",

"timespent":6000,

score:99}

{"userId":"u04",

"courseid":"c01",

"timespent":6000,

score:99}

{"userId":"u05",

"courseid":"c01",

"timespent":6000,

score:99}

{"userId":"u01",

"courseid":"c02",

"timespent":6000,

score:99}

{"userId":"u02",

"courseid":"c02",

"timespent":6000,

score:99}

{"userId":"u03",

"courseid":"c03",

"timespent":6000,

score:99}

{"_id":"c01"

"title":"Japanese159",

"description":"Japanese base",

"category":"language"}

{"_id":"c02"

"title":"Chinese200",

"description":"Chinese middle",

"category":"language"}

{"_id":"c03"

"title":"Political science 280",

"description":"Political middle",

"category":"politics"}

{"_id":"c04"

"title":"EE490",

"description":"electronic engineering hign",

"category":"Electronic"}

 

   集算器代码:



 

A1:连接MongoDB,连接字格式为mongo://ip:port/db?arg=value&…

         A2:统计出每门课的人数。这里使用aggregate函数从MongoDB中取数,该函数继承自mongdb,第1个参数是collection名,第2个参数是汇总表达式,遵循mongodb规范。计算结果是内存数据,如下:



 

         A3:Course中取出码表。这里使用find函数从MongoDB中取数,该函数继承自mongdb,第2个参数是过滤条件,写法遵循mongodb规范。Find的结果是游标,由于课程数量较少,因此用fetch函数将游标读入内存,结果如下:



 

         A4:使用switch函数将A3中的外键切换为A2中的记录,结果如下:



 

         A5:按对象方式访问内存,形成新的二维表,结果如下:



 

         A6:关闭mongodb连接。

猜你喜欢

转载自datamachine.iteye.com/blog/2228081