有谁知道为什么这种聚合仅匹配帖子,却不填充评论?
我需要评论集合中的用户评论,但只有空管道返回评论
Post.aggregate(...)
[
{
"$match": {
"author": ObjectId(...)
}
},
{
"$lookup": {
"from": "comments",
"let": {
"postID": "$post",
"isHiden": "$isHiden"
},
"pipeline": [
{
"$match": {
"$expr": {
"$and": [
{
"$eq": [
"$_id",
"$$postID"
]
},
{
"$eq": [
"$$isHiden",
0
]
}
]
}
}
}
],
"as": "comments"
}
}
]
评论对象包含
{
"_id": "5f7de8491af5c0e246d42609",
"isHiden": false,
"text": "...",
"post": "5f7de8491af5c0e246d42605"
}
帖子模型是
{
"_id": "5f7de8491af5c0e246d42605",
"title": "Corporate Web Coordinator",
"body": "...",
"author": "5f7de8491af5c0e246d42602"
}
}
我想得到像这样的结果
{
"_id": "5f7de8491af5c0e246d42605",
"confirm_status": "pending",
"title": "Dynamic Marketing Supervisor",
"body": "...",
"author": "5f7de8491af5c0e246d42604",
"comments": [
{ "_id": "5f7de8491af5c0e246d42609",
"isHiden": false,
"text": "...",
"post": "5f7de8491af5c0e246d42605" }
]
}
我尝试了一切,但无济于事...
我将不胜感激
答案 0 :(得分:1)
问题出在您的查询中,
$post
,isHiden
在发布表中不存在,您正在let
中定义该字段, $lookup: {
from: "comments",
let: { postID: "$_id" },
pipeline: [
{
$match: {
$expr: [
{
$eq: [
"$$postID",
"$post"
]
}
],
isHiden: false
}
}
],
as: "comments"
}