Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
MongoDB add count field in aggregation

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: {}}
       }
      }
    ])
about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!