'how to match _id and perticular array element in mongodb without using unwind

user data includes :

"_id" : 4
"username" : "smith"
likedVideos :[
           "videoId" : 10
           "title" : "something"
           "speaker" : "something"
           "description" : "something"
         ]

i have a collection with userId and a array of liked videos lists.liked videos(Array) includes videoId and video details. so i need to check that is the user is already liked this video or not. so how i match userId and videoId from the collection without using unwind ?

i tried :

  1. const data = await userModel.findOne({ _id : userId,likedVideos: { $elemMatch: { videoId : videoId } } }) but it returns all the data of that user.

  2. const alreadyLiked = await userModel.aggregate([ { $match: { '_id' : userId, 'likedVideos.videoId' : videoId, }, }, ]);

this also not working as expected.

I need a perfect solution to match a element inside array without using unwind (My boss said that unwind is a costly operation it will effect the app performance). can you please help me to solve this.



Solution 1:[1]

The best way to filter elements in a subarray is by using an Aggregation with $match and $project.

Example:

[{
  $match: { 
    _id: 'userId',
    likedVideos.videoId: 'videoId'
  }
}, {
  $project: {
    'likedVideos': {
      $filter: {
          input: '$likedVideos',
          as: 'item',
          cond: 
             {$eq: ["$$item.videoId","videoId"]}
      }
    }
  }
}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paplusc