Home > Back-end >  How to get the length of a string field in Mongoose?
How to get the length of a string field in Mongoose?

Time:02-11

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.

CodePudding user response:

you can use $strLenCP and $expr:

mongo playground

Article.find({
  "$expr": {
    "$gt": [
      {
        "$strLenCP": "$title"
      },
      3
    ]
  }
})

CodePudding user response:

You can also use aggregation query to achieve the result.

Article.aggregate(
[
  {
    '$project': {
      'titleLength': { '$strLenCP': '$name' }
    }
  }, {
    '$match': {
      'titleLength': {
        '$gt': 2
      }
    }
  }
])

CodePudding user response:

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);
  • Related