日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

MongoDB中實現多表聯查的實例教程_MongoDB

作者:山維空間 ? 更新時間: 2022-08-31 編程語言

前些天遇到一個需求,不復雜,用 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?類型。

總結

原文鏈接:https://blog.meathill.com/js/nodejs/mongodb-mongoose-support-left-join-filter.html

欄目分類
最近更新