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

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

0

you can use $strLenCP and $expr:

mongo playground

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

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

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