简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM