MongoDB: How to Find Length of String


You can use the following methods to find the length of a string in MongoDB and use this string length in queries:

Method 1: Find Length of String

db.myCollection.aggregate([
  { $project: {
        "name": 1,
        "length": { $strLenCP: "$name" }
  }}
])

Method 2: Find Documents with String Greater than Certain Length

db.myCollection.find({ 
    "name": { $exists: true },
    $expr: { $gt: [ { $strLenCP: "$name" }, 14 ] } 
})

The following examples show how to use each method with a collection teams with the following documents:

db.teams.insertOne({name: "Dallas Mavs", points: 31})
db.teams.insertOne({name: "San Antonio Spurs", points: 22})
db.teams.insertOne({name: "Houston Rockets", points: 19})
db.teams.insertOne({name: "Boston Celtics", points: 26})
db.teams.insertOne({name: "Cleveland Cavs", points: 33})

Example 1: Find Length of String

We can use the following code to calculate the length of the string in the “name” field of each document:

db.teams.aggregate([
  { $project: {
        "name": 1,
        "length": { $strLenCP: "$name" }
  }}
])

This code returns the following results:

{ _id: ObjectId("62014eff4cb04b772fd7a93d"),
  name: 'Dallas Mavs',
  length: 11 }
{ _id: ObjectId("62014eff4cb04b772fd7a93e"),
  name: 'San Antonio Spurs',
  length: 17 }
{ _id: ObjectId("62014eff4cb04b772fd7a93f"),
  name: 'Houston Rockets',
  length: 15 }
{ _id: ObjectId("62014eff4cb04b772fd7a940"),
  name: 'Boston Celtics',
  length: 14 }
{ _id: ObjectId("62014eff4cb04b772fd7a941"),
  name: 'Cleveland Cavs',
  length: 14 } 

The length value displays the length of the string in the “name” column.

For example:

  • The length of the string ‘Dallas Mavs’ is 11.
  • The length of the string ‘San Antonio Spurs’ is 17.

And so on.

Note that the length also counts blank spaces.

Example 2: Find Documents with String Greater than Certain Length

We can use the following code to return only the documents where the string in the “name” column is greater than 14:

db.teams.find({ 
    "name": { $exists: true },
    $expr: { $gt: [ { $strLenCP: "$name" }, 14 ] } 
})

This query returns the following results:

{ _id: ObjectId("62014eff4cb04b772fd7a93e"),
  name: 'San Antonio Spurs',
  points: 22 }
{ _id: ObjectId("62014eff4cb04b772fd7a93f"),
  name: 'Houston Rockets',
  points: 19 } 

Notice the the only two teams returned are the ones where the “name” field is greater than a length of 14.

Note: You can find the complete documentation for the $strLenCP function here.

Additional Resources

The following tutorials explain how to perform other common operations in MongoDB:

MongoDB: How to Split String into Array of Substrings
MongoDB: How to Concatenate Strings from Two Fields
MongoDB: How to Replace Strings in

Leave a Reply

Your email address will not be published.