- Published on
Mongodb $lookup 实现多表关联查询
- Authors
- Name
- Shelton Ma
使用场景
mongodb 查询时, 使用 lookup 等一系列操作实现。
...
{
$project: {
_id: 0,
project: 1,
},
},
{
$lookup: {
from: "users",
let: {
allUserIds: {
$setUnion: [
// list
{ $ifNull: ["$project.buyer", []] },
// string
{ $ifNull: [["$project.seller"], []] },
],
},
},
pipeline: [
{
$match: {
$expr: {
$in: ["$_id", "$$allUserIds"],
},
},
},
],
as: "user",
},
},
{
$project: {
project: {
title: "$project.title",
type: "$project.type",
users: {
$map: {
input: "$user",
as: "u",
in: {
userId: "$$u._id",
name: "$$u.name",
},
},
},
},
},
},
...