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

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

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 Denunciar

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 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