How to add count inside MongoDB aggregation. In this aggregation I'm sorting data by deep nested field "category". Catalog product is an ObjectId of catalog product. Inside catalog product I have an ObjectId of category.
products = await StorageModel.aggregate([
{ $lookup: { // Replace the Catelog Product ID with the Catelog Product
from: "catalogs",
localField: "catalogProduct",
foreignField: "_id",
as: "catalogs"
} },
{ $lookup: { // Replace the Category ID with the Category
from: "categories",
localField: "catalogs.category",
foreignField: "_id",
as: "catalogs.category"
} },
{ $addFields: { // Replace the Category with its name
"catalogs.category": "$catalogs.category"
} },
{ $match: {
"catalogs.category._id": { $in: ids }
} },
{ $lookup: { // Replace the Catelog Product ID with the Catelog Product
from: "catalogs",
localField: "catalogProduct",
foreignField: "_id",
as: "catalogProductNew"
} },
{ $count: "count" },
{ $sort: { _id: -1 } },
{ $skip: (page - 1) * 8 },
{ $limit: 8 },
]);
Returns. But another data from aggregation was erased.
[ { count: 3 } ]