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

120
Visualizações
mongoose countDocuments multiple keys

I have setup a Node get request to return the count of the keys in my database. However atm it returns the count of one key. I'd like to know how to add more keys to count. So instead of only counting Medium, I'd also like to count Small and Large.

    registerRoute.route("/countDocuments").get(function (req, res) {
   Sweatersizes.countDocuments({ sweatersize: "Medium" }, function (err, result) {
    if (err) {
      res.send(err);
    } else {
      res.json(result);
    }
  });
});

Thanks!
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Query

  • you can use group, and sum them seperatly

Test code here

aggregate(
[{"$group": 
   {"_id": "$sweatersize",
    "count": {"$sum": 1},
    "sweatersize": {"$first": "$sweatersize"}}},
 {"$unset": ["_id"]}])
about 4 years ago · Juan Pablo Isaza Relatório

0

You can do it with Aggregation framework and group pipeline:

registerRoute.route("/countDocuments").get(function (req, res) {
   Sweatersizes.aggregate([
     {
       "$group": {
         "_id": "$sweatersize",
         "total_count": {
           "$count": {}
         }
       }
     }
    ], function (err, result) {
      if (err) {
        res.send(err);
      } else {
        res.json(result);
      }
   });
});

Working example

about 4 years ago · Juan Pablo Isaza Relatório

0

Thanks the both of you! This is de code that eventually responded how I wanted it to:

registerRoute.route("/countDocuments").get(function (req, res) {
  Sweatersize.aggregate([
    {
      $group: {
        count: { $sum: 1 },
        sweatersize: { $first: "$sweatersize" },
      },
    },
  ])
    .then((result) => {
      res.json(result);
    })
    .catch((error) => {
      console.log(error);
    });
});
about 4 years ago · Juan Pablo Isaza 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