How to add count inside of MongoDB aggregation. My document in collection looks like this:
{
_id,
Sat,
calories,
carbs,
category,
fat,
fiber,
food,
grams,
measure,
protein,
sat.fat
}
I want to do query which will return all documents where "food" is like string and I want to project only fields which user select in frontend (for example, only "protein" and "carbs"). Also I want to add count field which will count found documents. So output should look something like this:
{
nutrientList: [
// here come all found projected documents
],
count: numberOfFOundDocs
}
I tried with, but it doesnt work:
const { macros, foodName, skip } = req.body;
// search word
var keywords = [
foodName,
foodName.toLocaleLowerCase(),
foodName.toLocaleUpperCase(),
foodName.toLowerCase(),
foodName.toUpperCase(),
],
regex = keywords.join("|");
Nutrient.aggregate([
{ $match: { food: { $regex: regex } } },
{
$project: {
protein: {
$cond: {
if: { $eq: [false, macros.protein] },
then: "$$REMOVE",
else: "$protein",
},
},
carbs: {
$cond: {
if: { $eq: [false, macros.carbohydrate] },
then: "$$REMOVE",
else: "$carbs",
},
},
fat: {
$cond: {
if: { $eq: [false, macros.fat] },
then: "$$REMOVE",
else: "$fat",
},
},
"sat.fat": {
$cond: {
if: { $eq: [false, macros.satFat] },
then: "$$REMOVE",
else: "$sat.fat",
},
},
fiber: {
$cond: {
if: { $eq: [false, macros.fiber] },
then: "$$REMOVE",
else: "$fiber",
},
},
calories: 1,
food: 1,
grams: 1,
measure: 1,
category: 1
},
},
{
$addFields: {
'totalCount': {$count: {}}
}
}
])