MongoDB中实现多表联查的实例教程

2022-07-13,,

前些天遇到一个需求,不复杂,用 sql 表现的话,大约如此:

select *
from db1 left join db2 on db1.a = db2.b
where db1.userid='$me' and db2.status=1

没想到搜了半天,我厂的代码仓库里没有这种用法,各种教程也多半只针对合并查询(即只筛选 db1,没有 db2 的条件)。所以最后只好读文档+代码尝试,终于找到答案,记录一下。

  • 我们用 mongoose 作为连接库
  • 联查需要用 $lookup
  • 如果声明外键的时候用 objectid,就很简单:
// 假设下面两个表 db1 和 db2
export const db1schema = new mongoose.schema(
  {
    userid: { type: string, index: true },
    couponid: { type: objectid, ref: db2schema },
  },
  { versionkey: false, timestamps: true }
);
export const db2schema = new mongoose.schema(
  {
    status: { type: boolean, default: 0 },
  },
  { versionkey: false, timestamps: true }
);

// 那么只要
db1model.aggregate([
  {
    $lookup: {
      from: 'db2', // 目标表
      localfield: 'couponid', // 本地字段
      foreignfield: '_id', // 对应的目标字段
      as: 'source',
  },
  {
    $match: [ /* 各种条件 */ ],
  },
]);

但是我们没有用 objectid,而是用 string 作为外键,所以无法直接用上面的联查。必须在 pipeline 里手动转换、联合。此时,当前表(db1)的字段不能直接使用,要配合 let,然后加上 $$ 前缀;连表(db2)直接加 $ 前缀即可。

最终代码如下:

mongo.ts

// 每次必有的条件,当前表的字段用 `$$`,连表的字段用 `$`
const filter = [{ $eq: ['$$userid', userid] }, { $eq: ['$isdeleted', false] }];
if (status === expired) {
  dateop = '$lte';
} else if (status === normal) {
  dateop = '$gte';
  filter.push({ $in: ['$$status', [normal, shared]] });
} else {
  dateop = '$gte';
  filter.push({ $eq: ['$$status', status] });
}
const results = await mymodel.aggregate([
  {
    $lookup: {
      from: 'coupons',
      // 当前表字段必须 `let` 之后才能用
      let: { couponid: '$couponid', userid: '$userid', status: '$status' },
      // 在 pipeline 里完成筛选
      pipeline: [
        {
          $match: {
            $expr: {
              // `$tostring` 是内建方法,可以把 `objectid` 转换成 `string`
              $and: [{ $eq: [{ $tostring: '$_id' }, '$$couponid'] }, ...filter, { [dateop]: ['$endat', new date()] }],
            },
          },
        },
        // 只要某些字段,在这里筛选
        {
          $project: couponfields,
        },
      ],
      as: 'source',
    },
  },
  {
    // 这种筛选相当 left join,所以需要去掉没有连表内容的结果
    $match: {
      source: { $ne: [] },
    },
  },
  {
    // 为了一次查表出结果,要转换一下输出格式
    $facet: {
      results: [{ $skip: size * (page - 1) }, { $limit: size }],
      count: [
        {
          $count: 'count',
        },
      ],
    },
  },
]);

同事告诉我,这样做的效率不一定高。我觉得,考虑到实际场景,他说的可能没错,不过,早晚要迈出这样的一步。而且,未来我们也应该慢慢把外键改成 objectid 类型。

总结

到此这篇关于mongodb中实现多表联查的文章就介绍到这了,更多相关mongodb多表联查内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《MongoDB中实现多表联查的实例教程.doc》

下载本文的Word格式文档,以方便收藏与打印。