mongo同库联表查询
发布于 7 年前 作者 masongzhi 4265 次浏览 来自 分享

原地址 这里只对同库联表查询做介绍,跨库联表查询可能在之后也会介绍(因为公司架构变动,之后可能会联表查询) 我用到的联表查询有两种,一种是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中填充外键

1 回复

使用populate时,耗时比嵌套的查询时间要长不少,我测过的,你可以试试。

回到顶部