「パズル」の投稿を正しく理解している場合(投稿のタイトルと編集 さまざまなユースケースです)、単一の$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