Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

353
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!