首页 > 数据库 > MongoDB > 正文

mongodb做联表查询的方法是什么?

2022-07-04 18:38:00
字体:
来源:转载
供稿:网友
       有些需求会需要我们对数据库做联表查询操作,在SQL中的连表查询大家可能比较熟悉,但是不是很了解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以上貌似可以转,没试过)。



(编辑:错新网)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表