Si j'ai bien compris le post "puzzle" (Titre du post et EDIT sont différents cas d'utilisation), nous pouvons obtenir le résultat souhaité avec un seul $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