use mongoose aggregate to retrieve data of array inside of a schema

I have a schema in MongoDB like this.

{
productID:1,
reviews:
[
{
_id:1
likes:[{userID:1},{userID:2}],
dislikes:[{userID:3},{userID:4}],
comment:"first comment"
},
{
_id:2
likes:[{userID:1},{userID:2}],
dislikes:[{userID:3},{userID:4}],
comment:"first comment"
}
]
}

I want to fetch the likes count of a userID of a particular review for example like count of userID 2 of review id 2. I tried to get it with the help of aggregate but got stuck.

this is the code that I tried.

  ProductReview.aggregate([
    { $match: { productID: productID } },
    { $match: {reviews._id:_id}}
 ])

but it looks like I am messing with the mongoose syntax. please help.

Answers 1

  • To get likes by user on particular reviews then use this query
    You will have to pass productID, reviewsID and userID

    db.collection.aggregate([
       {
            $match: {
                "productID": 1
            }
        },
        {
            $unwind: "$reviews"
        },
        {
            $match: {
                "reviews._id": 2
            }
        },
        {
            $unwind: "$reviews.likes"
        },
        {
            $match: {
                "reviews.likes.userID": 2
            }
        },
        {
            $group: {
                _id: "$reviews.likes",
                count: {
                    $sum: 1
                }
            }
        },
        {
            $project: {
                _id: 0,
                userID: "$_id.userID",
                count: 1
            }
        }
    ])
    

    Mongo Playground: https://mongoplayground.net/p/wUC5tbnLC47

    OLD This returns for all reviews Mongo Playground: https://mongoplayground.net/p/Ob5BLCAHrw1 if you want both likes and dislikes of users with one query you can use $facet Mongo Playground: https://mongoplayground.net/p/LELfQfKjw_h


Related Articles