https://mongoplayground.net/p/dsMlfEdSkXP
I want to query documents that the broadcasterUser upvoted. In the link, the broadcasterUser id is "23435553"
In the result, the document with "_id": ObjectId("5e7d7c35d86d85088863f4df")," should NOT be returned, because the broadcaster's voteType is "downVote".
The document with "_id": ObjectId("5e7d7c47d86d85088863f4e0") SHOULD be returned, because the broadcaster's voteType is "upVote".
Why is my $match condition not working?
{
$match: {
"votes.user.id": "23435553",
"votes.voteType": "upVote",
}
}
EDIT: Found my answer, thanks @prasad. https://mongoplayground.net/p/I_W0_BIIVVO
db.suggestions.aggregate([
{
$match: {
"channelId": "23435553",
}
},
{
$lookup: {
from: "votes",
localField: "_id",
foreignField: "suggestionId",
as: "votes"
}
},
{
$match: {
"votes": {
"$elemMatch": {
"user.id": "23435553",
"voteType": "upVote",
}
},
}
},
])
I wasn't trying to do any array filtering. I was trying to filter documents, based on the presence of an object in an array.
The desired logic with the 2nd $match operator was "find suggestion documents where, in the votes array, there exists an object with user.id="23435553" AND voteType="upVote".