I have used the $group pipeline and inside it, I have used $addToSet which has created an array of objects which contains two values - {subGenre (string), flag (bool)}. In the next pipeline of $project, I need to run a loop through this array and I need to select only that element of the array where flag is false.
So my code looks like this:
let data = await Books.aggregate(
[
{
$group: {
_id: genre,
price: { $sum: "$price" },
data: {
$addToSet: {
subGenre: "$subGenre",
flag: "$flagSelectGenre"
}
}
}
}
]
);
This would return documents like:
_id: {
genre: "suspense",
},
price: 10210.6,
data: [
{
subGenre: "Thriller",
flag: false,
},
{
subGenre: "jumpScare",
flag: true,
}
{
subGenre: "horror",
flag: false,
}
]
After this, I need to run a $project pipeline where I have to only project that element of the data array where the flag is true. The flag will be true for only one element.
$project: {
price: "$price",
subGenre: {$...... } // some condition on data array??
}
The final output should look like this:
price: 10210.6,
subGenre: "jumpScare",