好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

mongodb实现同库联表查询方法示例

前言

最近在工作中遇到一个问题,需要对 mongodb 数据库进行 联表查询 操作,发现网上这方面的资料较少,无奈只能自己来实现了,下面话不多说了,来一起看看详细的介绍:

注意: 这里只对同库联表查询做介绍,跨库联表查询可能在之后也会介绍(因为公司架构变动,之后可能会联表查询)

我用到的联表查询有两种,一种是mongoose的 populate ,一种是 $lookup

一、populate

populate是使用外键关联子表

例如现在有一张订单表结构(动态外键):

?

1

2

3

4

5

6

var orderSchema = new mongoose.Schema({

  uid: { type: String, required: true }, // 用户id

  amount: { type: Number, required: true },

  oType: { type: Number, required: true }, // 订单类型

  status: { type: Number, required: true }, // 订单的状态:1完成 2未完成 3失效

})

用户表:

?

1

2

3

4

5

6

var userSchema = new mongoose.Schema({

  phone: String,

  status: String,

  createdAt: Date,

  updatedAt: Date

})

现在我想根据查询order表,并返回对应用户phone字段

?

1

2

3

4

5

6

7

8

9

10

11

12

13

order.find().populate({path: 'uid', model: User, select: '_id real_name phone bankcard'}).exec(function(err, order) {

  // order: {

  // uid: {

  // phone: '15626202254',

  // status: "expand",

  // createdAt: Date,

  // updatedAt: Date

  // },

  // amount: 5000,

  // oType: 2, // 订单类型

  // status: 1, // 订单的状态:1完成 2未完成 3失效

  // }

});

这里order表的uid指向了user表的_id字段,当然也可以在新建表的时候定义外键,这里就不细说了

二、$lookup

lookup就是使用aggregate的$lookup属性,直接上官网例子非常好懂

orders表

?

1

2

3

{ "_id" : 1, "item" : "abc", "price" : 12, "quantity" : 2 }

{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1 }

{ "_id" : 3 }

inventory表

?

1

2

3

4

5

6

{ "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120 }

{ "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80 }

{ "_id" : 3, "sku" : "ijk", description: "product 3", "instock" : 60 }

{ "_id" : 4, "sku" : "jkl", description: "product 4", "instock" : 70 }

{ "_id" : 5, "sku": null, description: "Incomplete" }

{ "_id" : 6 }

?

1

2

3

4

5

6

7

8

9

10

11

db.orders.aggregate([

  {

  $lookup:

  {

   from: "inventory",

   localField: "item",

   foreignField: "sku",

   as: "inventory_docs"

  }

  }

])

就是使用order的item字段作为inventory表的查询条件{sku: item},并赋值给inventory_docs字段,但值得注意的是两个字段的类型必须一样(3.5以上貌似可以转,没试过)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

参考文章

Mongoose中的关联表查询 && 聚合查询

在mongoose中填充外键

原文链接:http://www.jianshu.com/p/f7f531c9e676

查看更多关于mongodb实现同库联表查询方法示例的详细内容...

  阅读:18次