MongoDB中实现多表联查的实例教程(mongodb 表关联)深度揭秘

随心笔谈1年前 (2023)发布 admin
120 0

// 每次必有的条件,当前表的字段用 `$$`,连表的字段用 `$`
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’,
},
],
},
},
]);

© 版权声明

相关文章