mongodb - $in 需要一个数组作为第二个参数
问题描述
我正在尝试进行一些聚合,但遇到以下问题。我需要使用“管道”,当我正在寻找的数组丢失时出现错误。
{
$lookup: {
from: 'comments',
let: { comments: '$comments' },
pipeline: [
{
$match: {
$expr: {
$in: ['$_id', '$$comments']
},
isDeleted: false
}
}
],
as: 'comments'
}
}
在这个阶段,我收到以下错误:
'$in requires an array as a second argument, found: missing'
因为并非所有文档都有“评论”字段。
注意:我使用的是管道而不是foreingField和localField,因为我需要使用isDeleted: false
可能还有其他匹配条件进行过滤。
仅当文档具有字段注释时才进行此查找吗?
谢谢!
解决方案
您可以在中添加$ifNull
或$and
不为空或存在条件$expr
{
$lookup: {
from: 'comments',
let: { comments: '$comments' },
pipeline: [
{
$match: {
$expr: {$and: [
{$in: ['$_id', {$ifNull :['$$comments',[]]}]},
{$eq: ["$isDeleted", false]}
]}
}
}
],
as: 'comments'
}
}
推荐阅读
- git - 如何使用来自开放 PR 的压缩提交来启动一个新分支?
- python - 访问在 SQL Server 2017 上执行的 Python 脚本的 JSON 结果
- javascript - 根据数组内容预选复选框
- excel - Excel VBA代码从另一张表中减去数量
- c# - 在通用 Windows 应用 (XAML) 中启用后退/前进和刷新手势
- javascript - 将数字转换为所需的货币格式
- firebase - SwiftUI:从 DetailView 更新 Firestore
- python - Python Numba:存储在类中的抖动函数
- python - 我需要一个函数来根据变量返回 RGBA 值
- javascript - 如何在javascript中对嵌套的JSON数组进行排序