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

183
Vistas
How to get the length of a string field in Mongoose?

I am new to MongoDB and Mongoose.

I am practicing some of the queries with the following Schema and Model:

const articleSchema = mongoose.Schema({
  title: String,
  content: String,
});

const Article = mongoose.model('article', articleSchema);

Let's say I added the following two documents:

{title: "One", content: "Content One"}
{title: "LongerTitleThanOne", content: "Content Two"}

Which query can I use to find all documents where the "title" length is greater than 3?
I tried the following query but it only works with numbers:

Article.find({title:{$gt:3}}, (err,foundItems)=>{});

Many thanks in advance for your help here.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

you can use $strLenCP and $expr:

mongo playground

Article.find({
  "$expr": {
    "$gt": [
      {
        "$strLenCP": "$title"
      },
      3
    ]
  }
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can also use aggregation query to achieve the result.

Article.aggregate(
[
  {
    '$project': {
      'titleLength': { '$strLenCP': '$name' }
    }
  }, {
    '$match': {
      'titleLength': {
        '$gt': 2
      }
    }
  }
])
about 4 years ago · Juan Pablo Isaza Denunciar

0

This is not the best way to do this but it works

I advise you to not use this in production.

First get all your data from you database and store it in a variable then use JavaScript filter function to accomplish your task

For Example

     let data = model.find({});
     let filter_data = data.filter(data.title.length>8);
about 4 years ago · Juan Pablo Isaza 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