Ale*_*scu 6 mongoose mongodb mongodb-query aggregation-framework
我正在尝试进行一些聚合,但遇到以下问题。我需要使用“管道”,当我正在寻找的数组丢失时,我收到一个错误。
{
$lookup: {
from: 'comments',
let: { comments: '$comments' },
pipeline: [
{
$match: {
$expr: {
$in: ['$_id', '$$comments']
},
isDeleted: false
}
}
],
as: 'comments'
}
}
Run Code Online (Sandbox Code Playgroud)
在这个阶段,我收到以下错误:
'$in requires an array as a second argument, found: missing'
因为并非所有文档都有“评论”字段。
注意:我使用管道而不是foreingField和localField ,因为我需要使用isDeleted: false其他匹配条件进行过滤。
无论如何,仅当文档具有字段注释时才进行此查找?
谢谢!
Sar*_*ana 11
您可以添加$ifNull或$and不为空或存在条件$expr
{
$lookup: {
from: 'comments',
let: { comments: '$comments' },
pipeline: [
{
$match: {
$expr: {$and: [
{$in: ['$_id', {$ifNull :['$$comments',[]]}]},
{$eq: ["$isDeleted", false]}
]}
}
}
],
as: 'comments'
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2645 次 |
| 最近记录: |