Rails- Mongoid 查询以根据字段长度过滤对象

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

我想根据字段的长度过滤集合。 示例:对于集合乐队,我想要乐队名称长度等于 10 的对象。

我认为有两种方法可以做到这一点。在这些示例中,假设我有以下模型:

class Band
  include Mongoid::Document

  field :name, type: String
end

聚合

如果您使用的是 MongoDB 服务器版本 3.6 或更高版本,您可以使用 $expr operator to include aggregation operations in your query. In this example, I'm using the $strLenCP 运算符查找 name 字段具有 5 个 Unicode 代码点的任何文档:

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

正则表达式

您还可以使用 Ruby 正则表达式来匹配任何五个字符的字符串:

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

我怀疑聚合会更高效,但了解一些做某事的方法也没什么坏处。