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

118
Views
Get count of a value of a subdocument inside an array with mongoose

I have Collection of documents with id and contact. Contact is an array which contains subdocuments.

image of the document

I am trying to get the count of contact where isActive = Y. Also need to query the collection based on the id. The entire query can be something like

Select Count(contact.isActive=Y) where _id = '601ad0227b25254647823713'

I am using mongo and mongoose for the first time. Please edit the question if I was not able to explain it properly.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use an aggregation pipeline like this:

  • First $match to get only documents with desired _id.
  • Then $unwind to get different values inside array.
  • Match again to get the values which isActive value is Y.
  • And $group adding one for each document that exists (i.e. counting documents with isActive= Y). The count is stores in field total.
db.collection.aggregate([
  {
    "$match": {"id": 1}
  },
  {
    "$unwind": "$contact"
  },
  {
    "$match": {"contact.isActive": "Y"}
  },
  {
    "$group": {
      "_id": "$id",
      "total": {"$sum": 1}
    }
  }
])

Example here

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!