Select string length in mongodb

user1018364 picture user1018364 · Feb 1, 2013 · Viewed 17k times · Source

How do you query mongodb to find the length of a particular string/text field?

And how would you find the max length of a query set?

Answer

Philipp picture Philipp · Feb 1, 2013

Unfortunately the aggregation framework doesn't support a "len" operator to automatically convert strings to their length while you do a query. So you have to solve this in your own code. You could

  1. use a MapReduce function to calculate string lengths
  2. query for the strings and calculate their length on the application layer

The difference between these method is that the first runs on the database while the latter runs on your application server. I would recommend the latter option, because MapReduce can be very slow and cumbersome to use.