Trying to return this document from a collection by checking if a variable (userId
) matches the second element in users
array.
I created a playground. Expected result is the user document xyz
as thats the only user who liked rrr
and the user rrr
has not liked back – https://mongoplayground.net/p/WI7hqR7SIMh
Expected result:
[
{
"count": 1,
"users": [
{
"_id": "xyz",
"group": 1,
"name": "xyyy"
}
]
}
]
My query is below where variable userId
is xw5vk1s and is the second element in above array. The two conditions I am checking are like: true
and userId = second element is users array
const users = await db
.collection('users')
.aggregate([
{
$lookup: {
from: "likes",
let: {userId: "$_id"},
pipeline: [{$match: {$expr: {$and: [{like: true, "users.1": userId} ]}}}],
as: "valid"
}
},
{$match: {
"valid.0": {$exists: true},
}
},
{$unset: ["valid"]},
{$group: {_id: 0, users: {$push: "$$ROOT"}, count: {$sum: 1}}}
])
The query is not working.
2
Answers
** I hope this will solve your problem **
One option is using two
$lookup
s:rrr
$match
only the unpaireduser
data and format the responseSee how it works on the playground example