Nikhil Bajaj
Nikhil Bajaj

Reputation: 11

Rails- Mongoid query to filter objects based on length of a field

I want to filter a collection based on the length of a field. Example : For collection Band, i would want the objects where the length of the name of band is equal to 10.

Upvotes: 0

Views: 402

Answers (1)

egiurleo
egiurleo

Reputation: 106

There are two ways I can think to do this. In these examples, let's pretend I have the following model:

class Band
  include Mongoid::Document

  field :name, type: String
end

Aggregation

If you're using MongoDB server version 3.6 or newer, you can use the $expr operator to include aggregation operations in your query. In this example, I'm using the $strLenCP operator to find any documents where the name field has 5 Unicode code points:

Band.where("$expr": { "$eq": [ { "$strLenCP": "$name" }, 5 ] })

Regular Expressions

You could also use a Ruby regular expression that matches any five-character string:

Band.where(name: /\A.{5}\z/)

I suspect aggregation will be more performant, but it can't hurt to know a few ways of doing something.

Upvotes: 3

Related Questions