I have this aggregate query returning the title and number of user likes for the post which is working.
const posts = await Post.aggregate([
{ $project:
{
title:1,
userlikecnt:{$size:"$userlikes"}
}
}
])
I'm trying to extend it to include if the specific user like that post, then return true/false or if not then a count. This is what I have thus far but it isn't working, any suggestions?
const posts = await Post.aggregate([
{ $project:
{
title:1,
userlikecnt:{$size:"$userlikes"},
userlikedthisPost:{$sum:{
$cond:[{$eq:['$userlikes.userid',
mongoose.Types.ObjectId('64b4717b9c74dbff21f51e0e') ]},1,0] }}
}
}
])
The $eq
check doesn't do what you are looking for here with arrays inside of the aggregation language.
Instead try the $in
operator (being sure to flip the order of the arguments). Something like this:
.aggregate([
{
$project: {
title: 1,
userlikecnt: {
$size: "$userlikes"
},
userlikedthisfilm: {
$sum: {
$cond: [
{
$in: [
3,
"$userlikes.userid"
]
},
1,
0
]
}
}
}
}
])
Note in the playground I used integers rather than ObjectIds for the userid
field of userlikes
, be sure to use appropriate types/values for your specific situation