Query MongoDB with length criteria?

To query MongoDB with length criteria, you can use the $regex operator with regular expressions to match string fields based on their character length.

Syntax

db.collection.find({
    "fieldName": { $regex: /^.{minLength,maxLength}$/ }
});

Where minLength and maxLength define the character count range.

Sample Data

db.queryLengthDemo.insertMany([
    {"StudentFullName": "John Smith"},
    {"StudentFullName": "John Doe"},
    {"StudentFullName": "David Miller"},
    {"StudentFullName": "Robert Taylor"},
    {"StudentFullName": "Chris Williams"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

Example: Query Names with 9-12 Characters

db.queryLengthDemo.find({
    "StudentFullName": { $regex: /^.{9,12}$/ }
});
{
    "_id": ObjectId("5c9a01ae353decbc2fc927c0"),
    "StudentFullName": "John Smith"
}
{
    "_id": ObjectId("5c9a01c2353decbc2fc927c2"),
    "StudentFullName": "David Miller"
}

How It Works

  • ^ ? matches the beginning of the string
  • . ? matches any character
  • {9,12} ? specifies the length range (9 to 12 characters)
  • $ ? matches the end of the string

Conclusion

Use $regex with the pattern /^.{min,max}$/ to filter MongoDB documents by string field length. This approach is useful for validating data formats or finding entries within specific character ranges.

Updated on: 2026-03-15T00:29:10+05:30

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements