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

240
Visualizações
Filtering and measuring mongodb nested array of objects

I have a document of this kind:

{
 _id: "123",
 arrayName: [
         { text: 'first', field: false},
         { text: 'second', field: true},
         { text: 'third', field: false}
            ]
}

Now I would like to my query to return the length of filtered arrayName to have only the objects where field === false.

I have tried many queries with db.collection.find({}) but I always receive the entire document and in the end and it count() => to 1.

Any suggestion? thanks

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can use projection operator to achieve what you want.

Try this:

db.collection.find({
    _id : givenId ,
    "arrayName.field" : false
},{
    "arrayName.$":1
},function(err,result){
   if(!err){
       len = result.arrayName.length;
       //use len however you want.
   }
});

"arrayName.$":1 will select only the matched elements of the array. Then you can get the length of array with field:false

Hope this helps!

over 4 years ago · Santiago Trujillo Relatório

0

Another user already give you the right answer for your question using the plain Mongo query. But I think it won't have much because you are using Mongo with Meteor, so here I present you another way to solve your problem by using transform function in find command:

Collection.find({
  // ...
}, {
  transform(doc) {
    doc.filterArrayLength = doc.arrayName.filter(obj => obj.field === false).length;

    return doc;
  }
}).fetch();

With this command the result will be like:

[
  // ...
  {
    _id: "123",
    arrayName: [
      {
        text: 'first',
        field: false
      }, {
        text: 'second',
        field: true
      }, {
        text: 'third',
        field: false
      }
    ],
    filterArrayLength: 2
  }
]
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