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

随心笔谈2年前发布 admin
199 0 0

文章摘要

这篇文章主要介绍了如何使用MongoDB的聚合查询功能来处理复杂的数据筛选和连接操作。文章通过示例展示了如何根据`status`字段的不同值,使用不同的比较操作符(如`$eq`和`$in`)和条件判断来过滤数据。此外,文章还详细讲解了如何利用`$lookup`连接`coupons`表,并通过`$facet`聚合结果,实现高效的数据查询和处理。文章的核心内容在于展示MongoDB聚合查询的强大功能及其在实际应用中的使用场景和技巧。

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

© 版权声明

相关文章