Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda