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

346
Vistas
Mongodb find array length greater than specified size

I have this Mongoose model schema

const postSchema = new Schema({

  title: String,

  headline: [{
    kind: String,
    id: Schema.Types.ObjectId,
    content: String,
    relevance: Number,
    _id: false
  }],

});

I want to find models in the database where the headline array has a length greater than x

I have this query:

 const query = {
        'headline.kind': 'topic',
        'headline.id': topicId,
        'headline':{
            '$size':{
                '$gt': x
            }
        }
    };

but when I use this I get:

 { MongooseError: Cast to number failed for value "{ '$gt': 2 }" at path "headline"
    at CastError (/home/oleg/WebstormProjects/lectal/api/node_modules/mongoose/lib/error/cast.js:26:11)

anyone know the right way to construct this query? (In my code I just hardcoded the number 2 for x.)

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

For the most efficient way you can do this with a "dot notation" by specifying the n position. Which is basically saying if an array has "at least" n + 1 elements then return it.

So rather than writing { "$gt": 2 } you instead look for the presence of the index value of the "third" element ( from zero index third is 2 ):

{ "headline.2": { "$exists": true } }

The $exists operator is looking for the presence of an element at that given index, and when the condition is met then the array must be of at least that length and therefore "greater than two"

Also noting that your query condition want's to match several properties on an array element, and for this you actually use $elemMatch, otherwise the conditions actually apply to matching any element in the array, and not just the one with "both" conditions as $elemMatch does.

{
  "headline": { "$elemMatch": { "kind": "topic", "id": topicId } },
  "headline.2": { "$exists": true }
}

to do that "dynamically", we merely build the query generating the key from the parameter:

const query = {
  "headline": { "$elemMatch": { "kind": "topic", "id": topicId } }
};

query['headline.'+x] = { "$exists": true }
over 4 years ago · Santiago Trujillo Denunciar

0

From what I've read it is not possible to do that using a $size and $gt.

Try using $where - http://mongoosejs.com/docs/api.html#query_Query-%24where

over 4 years ago · Santiago Trujillo Denunciar

0

$expr:{$gte: [{$size: "$preferredArray"}, specifiedsize]}

If you're using aggregate its better and faster; the entire query would look like this:

db.collection.aggregate([
 
  {
      $match: {
          preferred criteria:1,
          $expr:{$gte: [{$size: "$diagnosis"}, 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