EDIT: My original question was
MongoDb Aggregation: Can you $unwind an input document variable in the pipline of a $lookup stage?
Consider the code below:
{$lookup: {
from:"mydoc",
let: {"c":"$myArray"},
pipeline: [
{$unwind: "$$c"},
]
as:"myNewDoc"
}}
How would I unwind c
if I wanted to?
/////END OF ORIGINAL QUESTION
-----EDIT-----
From Tom Slabbaert's comment we now know that it is possible to $unwind an input document variable in the pipline of a $lookup stage. But it is not recommended.
What am I trying to achieve?
Consider these collections, poll
and castedvote
from this answer from a question I had asked.
I am trying to get an output like below:
numberOfVotes: 6,
hasThisUserVoted: true,
numberOfComments: 12,
castedVotesPerChoice:{
"choiceA": [
{"_id": ObjectId("..."), "voter": "Juzi", "choice": 0, "pollId": 100 },
{"_id": ObjectId("..."), "voter": "Juma", "choice": 0, "pollId": 100 },
{"_id": ObjectId("..."), "voter": "Jane", "choice": 0, "pollId": 100 },
],
"choiceB": [
{"_id": ObjectId("..."), "voter": "Jamo", "choice": 1, "pollId": 100 },
{"_id": ObjectId("..."), "voter": "Juju", "choice": 1, "pollId": 100 },
{"_id": ObjectId("..."), "voter": "Jana", "choice": 1, "pollId": 100 }
],
"choiceC": [ ]
}
my current implementation:
db.poll.aggregate([
{"$match": {"_id": 100}},
// ...lookup to get comments
{"$lookup": {
"from":"castedvotes",
"let": {"pollId":"$_id"},
"pipeline":[
{"$match":
{"$expr":
{"$eq": ["$pollId", "$$pollId"]},
}},
],
"as":"votes" // will use this to get number of votes and find out if the authenticated user has voted.
}},
{"$unwind":"$choices"},
{"$lookup": {
"from":"castedvotes",
"let": {"c":"$choices"},
"pipeline":[
{"$match":
{"$expr":
{"$eq": ["$choice", "$$c.id"]},
}},
],
"as":"votesPerChoice"
}},
])
The issue I have with my current implementation is that it is doing a lookup on the same collection twice I feel like this is unnecessary and it makes the code not dry.
With $unwind
I know I can un-$unwind
as described here.
So my question is how can I get my desired output with one $lookup to the casted vote collection? Since both lookups return the same data.
Or to ask the question differently how can I group an array-1 based on another array-2 in mongodb aggregation when given array-1 and array-2?
This question answers how to group arrays based on another array in mongodb aggregation by structuring the $lookup
stage a certain way. It does not answer my question.