数据库表如下:
acticles集合:
acticlesMaptags集合:
tags集合:
需求:
查询所有article返回article的所有信息同时携带article对应的所有标签。
db.acticles.aggregate([
{
$addFields: {
_id: { $toString: "$_id" }
}
},
{
$lookup:
{
from:"acticlesMaptags",
localField:"_id",
foreignField:"acticleid",
as:"tag"
}
},
{
$unwind:
{
path:"$tag"
}
},
{
$addFields: {
tag: { $toObjectId: "$tag.tagid" }
}
},
{
$lookup:
{
from:"tags",
localField:"tag",
foreignField:"_id",
as:"tag"
}
},
{
$addFields: {
tag: { $arrayElemAt: ["$tag", 0] }
}
},
{
$group:
{
_id: "$_id",
title: { $first: "$title" },
descripe: { $first: "$descripe" },
time: { $first: "$time" },
text: { $first: "$text" },
tagdata: { $push: "$tag" }
}
}
]
)
查询结果
之后有时间我会整理这个里面的知识点。