I have a table named histories. here is a sample of documents,
{ "_id": "6354e4210490e6f3dd109fb7", "type": "like", "bookId": "6329af1b1c67cc8eaf26fe42", "userId": "635122ea40ef5d60e653fc9e", "createdAt": "2022-10-23T06:50:09.166Z", "updatedAt": "2022-10-23T06:50:09.166Z", "__v": 0 },
{ "_id": "6354e4210490e6f3dd109fb9", "type": "share", "bookId": "6322db5464c70448ad0282d4", "userId": "6301e9f243719de7e0637acf", "createdAt": "2022-10-23T06:50:09.167Z", "updatedAt": "2022-10-23T06:50:09.167Z", "__v": 0 }
now i have to show a list of distinct bookId with its total likes, shares and dislikes count using aggregate in mongodb..
CodePudding user response:
You can try with
db.histories.aggregate([
{
$group: {
_id: "$bookId" ,
likes: {
"$sum": { $cond: { if: { "$eq": ["$type", "like"]}, then: 1, else: 0 }}
},
dislikes: {
"$sum": { $cond: { if: { "$eq": ["$type", "dislike"]}, then: 1, else: 0 }}
},
shares: {
"$sum": { $cond: { if: { "$eq": ["$type", "share"]}, then: 1, else: 0 }}
},
}
},
])