Search code examples
mongodbaggregate

Display true or false if a user ID exist within an array of objects in an aggregate query


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"}
        }
      }
    ])

array of userIDs

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] }}
        }
      }
    ])

Solution

  • 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
              ]
            }
          }
        }
      }
    ])
    

    Playground demonstration

    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