我有一个聚合管道,我的文档当前采用以下格式:
{
"user": "5e3d326537df7e4dda73eb23",
"sharedWithGroups": [ "5e3d326437df7e4dda73eb13", "5e3d326437df7e4dda73eb19" ],
"userGroupIds": [ "5e3d326437df7e4dda73eb19" ]
}
其中 userGroupIds
是上一阶段的结果,我在其中找到用户所在组的 ID。
我正在尝试向管道添加一个匹配阶段,以查找具有与特定 ID 匹配的用户 ID 或具有包含以下条目之一的 sharedWithGroups
属性的所有文档userGroupIds
。
我认为这样的事情会起作用:
{
$match: {
$or: [
{ user: "5e3d326537df7e4dda73eb23" },
{ sharedWithGroups: { $in: "$userGroupIds" } }
]
}
}
但我收到错误:$in 需要一个数组
。我不明白,因为 $userGroupIds
绝对是一个数组。我尝试过使用 $expr,认为字段值可能无法解析,但没有运气。这种方法是否可行,或者是否有另一种/更好的方法来使用多个条件过滤这些文档?
最佳答案
你可以试试这个:
{
$match: {
$or: [
{ user: "5e3d326537df7e4dda73eb23" },
{ $expr: { $gt: [{ $size: { $setIntersection: ["$sharedWithGroups", "$userGroupIds"] } }, 0] } }
]
}
}
(或)
{
$match: {
$or: [
{ user: "5e3d326537df7e4dda73eb23" },
{ $expr: { $setIsSubset: ["$userGroupIds", "$sharedWithGroups"] } }
]
}
}
关于MongoDB聚合: Use field value of current document in $match $or query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60534653/