猫鼬聚合查找管道不起作用
Mongoose aggregation lookup pipeline doesn't work
知道为什么此聚合仅匹配 post,但不填充评论吗?
我需要来自评论集合的用户评论,但只有空管道 returns 条评论
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"
}
Post型号为
{
"_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" }
]
}
我尝试了所有方法,但没有任何效果...
我会很感激任何帮助
问题出在您的查询中,
- post 字段出现在注释 table 中并且您使用了 _id,因此它应该是
$post
,
- 内部管道字段
isHiden
不存在于 post table 中并且您在 let
中定义该字段,它应该是,
$lookup: {
from: "comments",
let: { postID: "$_id" },
pipeline: [
{
$match: {
$expr: [
{
$eq: [
"$$postID",
"$post"
]
}
],
isHiden: false
}
}
],
as: "comments"
}
知道为什么此聚合仅匹配 post,但不填充评论吗?
我需要来自评论集合的用户评论,但只有空管道 returns 条评论
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"
}
Post型号为
{
"_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" }
]
}
我尝试了所有方法,但没有任何效果...
我会很感激任何帮助
问题出在您的查询中,
- post 字段出现在注释 table 中并且您使用了 _id,因此它应该是
$post
, - 内部管道字段
isHiden
不存在于 post table 中并且您在let
中定义该字段,它应该是,
$lookup: {
from: "comments",
let: { postID: "$_id" },
pipeline: [
{
$match: {
$expr: [
{
$eq: [
"$$postID",
"$post"
]
}
],
isHiden: false
}
}
],
as: "comments"
}