Reputation: 2193
I have an aggregation pipeline and my documents are currently in the following format :
{
"user": "5e3d326537df7e4dda73eb23",
"sharedWithGroups": [ "5e3d326437df7e4dda73eb13", "5e3d326437df7e4dda73eb19" ],
"userGroupIds": [ "5e3d326437df7e4dda73eb19" ]
}
Where userGroupIds
is the result of a previous stage, where I find the IDs of the groups that the user is in.
I'm trying to add a match stage to the pipeline to find all documents which have either a user ID that matches a specific ID, OR have a sharedWithGroups
property that contains one of the entries in userGroupIds
.
I thought that something like this would work :
{
$match: {
$or: [
{ user: "5e3d326537df7e4dda73eb23" },
{ sharedWithGroups: { $in: "$userGroupIds" } }
]
}
}
But I get an error: $in needs an array
. I don't understand because $userGroupIds
is definitely an array. I've tried using $expr, thinking that the field value may not be resolving, but have had no luck. Is this approach possible, or is there another/better way to filter these documents using multiple criteria?
Upvotes: 2
Views: 1380
Reputation: 17935
You can try this :
{
$match: {
$or: [
{ user: "5e3d326537df7e4dda73eb23" },
{ $expr: { $gt: [{ $size: { $setIntersection: ["$sharedWithGroups", "$userGroupIds"] } }, 0] } }
]
}
}
Test : MongoDB-Playground
(Or)
{
$match: {
$or: [
{ user: "5e3d326537df7e4dda73eb23" },
{ $expr: { $setIsSubset: ["$userGroupIds", "$sharedWithGroups"] } }
]
}
}
Test : MongoDB-Playground
Upvotes: 3