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

  • A+
所属分类:MongoDB

前语

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

留意:这儿只对同库联表查询做介绍,跨库联表查询可能在之后也会介绍(由于公司架构变化,之后可能会联表查询)

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

一、populate

populate是运用外键相关子表

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

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失效
})

用户表:

var userSchema = new mongoose.Schema({
 phone: String,
 status: String,
 createdAt: Date,
 updatedAt: Date
})

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

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表

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

inventory表

{ "_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 }
db.orders.aggregate([
 {
 $lookup:
 {
  from: "inventory",
  localField: "item",
  foreignField: "sku",
  as: "inventory_docs"
 }
 }
])

就是运用order的item字段作为inventory表的查询条件{sku: item},并赋值给inventory_docs字段,但值得留意的是两个字段的类型有必要一样(3.5以上形似能够转,没试过)

总结

以上就是这篇文章的全部内容了,希望本文的内容对我们的学习或许工作能带来一定的协助,假如有疑问我们能够留言沟通,谢谢我们对脚本之家的支持。

参阅文章

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

在mongoose中填充外键

 

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: