Query on string length in MongoDB

If you need to query on string length, you will need to use the $where operator. As per the documentation, you can pass either a string with a JavaScript expression or a JavaScript function.

The downside to this operation is that it operates on each document in the collection. As a result, it can be a slow. So use with caution.

For the examples below, lets consider a document with the following structure:

  "username": "brian",
  "addresses': [
       "address": "500 Grant Street",
       "city": "Pittsburgh",
       "state": "PA",
       "zip": "15219",
       "country": "US"
      "address": "405 Spray Ave",
      "city": "Banff",
      "state": "AB",
      "zip": "T1L1J4",
      "country": "CA"

String Expressions

So first thing, here's a simple JS expression in a string:

db.users.find({ $where: 'this.username.length < 4' })  

The above example will find all documents in the users collection that have a username property with a length less than 4 characters.

You'll notice that in the expression, the reference to the document is made with this.

The string expressions will work for property or sub-document access and is straightforward for simple queries.

Function Expressions

If you have to work with Arrays or more complicated queries across multiple properties, you will need to use the function based approach.

This is similar to the string based approach, except you pass in a function to execute for each document:

  $where: function() {
    for(var i = 0; i < this.addresses.length; i++) {
      var address = this.addresses[i];
      if(address.state.length > 2) {
        return true;

The above function will iterate over the addresses array and look at the length of each . It will look at the state property of each address and see if the length is larger than 2 characters.


Hopefully this helps you understand how string queries work in MongoDB.

comments powered by Disqus