Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda