EDIT: My original question was
MongoDb Aggregation: Can you $unwind an input document variable in the pipline of a $lookup stage?
Co
If I've understood the "puzzle" post correctly (Post title and EDIT are different use cases), we can get the desired result with a single $lookup
:
db.poll.aggregate([
{
"$match": {
"_id": 100
}
},
{
"$lookup": {
"from": "castedvotes",
"localField": "pollId",
"foreignField": "choices.id",
"as": "voters"
}
},
{
$project: {
numberOfVotes: {
$size: "$voters"
},
hasThisUserVoted: {
$in: [
"$_id",
"$voters.pollId"
]
},
/**How to calculate it?*/
numberOfComments: {
$multiply: [
{
$size: "$voters"
},
2
]
},
castedVotesPerChoice: {
$arrayToObject: {
$map: {
input: "$choices",
as: "choice",
in: {
k: "$$choice.name",
v: {
$filter: {
input: "$voters",
as: "voter",
cond: {
$eq: [
"$$voter.choice",
"$$choice.id"
]
}
}
}
}
}
}
}
}
}
])
MongoPlayground