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

151
Views
MongoDB - Count value occurrences for field

Document structure

{
"A": "1",
"B": "3",
"C": "0.000090213",
},
{
"A": "1",
"B": "3",
"C": "0.000037698",
},
{
"A": "2",
"B": "4",
"C": "0.00016664",
}

I'm trying to get the count of value for specific fields with aggregation, desired result for A and B would be

A: { "1": 2, "2": 1}
B: { "3": 2, "4": 1}

Any help is greatly appreciated.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

 db.collection.aggregate([
 {
  $facet: {
  "A": [
    {
      $group: {
        _id: "$A",
        v: {
          $sum: 1
        }
      }
    }
   ],
  "B": [
    {
      $group: {
        _id: "$B",
        v: {
          $sum: 1
        }
      }
     }
   ]
  }
  },
  {
   $addFields: {
   A: {
    $map: {
      input: "$A",
      as: "a",
      in: {
        k: "$$a._id",
        v: "$$a.v"
      }
     }
    }
  }
 },
 {
   $addFields: {
     B: {
      $map: {
      input: "$B",
      as: "b",
      in: {
        k: "$$b._id",
        v: "$$b.v"
      }
     }
    }
   }
  },
 {
   $project: {
    A: {
       "$arrayToObject": "$A"
       },
    B: {
    "$arrayToObject": "$B"
       }
      }
     }
   ])

Explained:

  1. $group the desired keys in two separate pipes with $facet
  2. $addFields to rename _id to k ( suitable for $arrayToObject )
  3. $project the desired counts with $arrayToObject.

playground

over 4 years ago · Santiago Trujillo Report
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!