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

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

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 Relatório

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 Relatório

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