Ruby on rails 使用长度条件查询MongoDB

Ruby on rails 使用长度条件查询MongoDB,ruby-on-rails,mongodb,mongoid,Ruby On Rails,Mongodb,Mongoid,我在MongoDB集合中有几个文档,其中有一个字段“name”(是字符串) 如何执行查询,如7您可以使用 User.where(“this.name.length>=7&&this.name.length您可以使用MongoDB的$where查询参数向服务器提交javascript。例如: db.myCollection.find( {$where: "(7 <= this.name.length) && (this.name.length <= 14)"} ) d

我在MongoDB集合中有几个文档,其中有一个字段“name”(是字符串)

如何执行查询,如
7您可以使用


User.where(“this.name.length>=7&&this.name.length您可以使用MongoDB的$where查询参数向服务器提交javascript。例如:

db.myCollection.find( {$where: "(7 <= this.name.length) && (this.name.length <= 14)"} )

db.myCollection.find({$where:”(7
$where
查询效率不高


如果这是一个经常执行的查询,您可能希望将长度存储在一个单独的字段中。

Mongo提供了一些使用长度标准执行查询的方法–
$where
$regex
是两个很好的选择,但是由于查询性能更好,我建议使用
$regex


(较慢) 在查询中接受JavaScript表达式或函数 例如:

db.collection.find({ $where: 'this.name.length >= 7 && this.name.length <= 14' })
db.collection.find({ name: { $regex: /^.{7,14}$/ } })

注意:
$regex
操作符利用您的数据库索引,从而实现更快的查询(如果您的集合已正确索引).-

我猜你的意思是
this.name.length
就像上面Simone发布的那样?这个查询不有效,不会使用索引!我知道,但它没有要求最有效的方法。最有效的方法是添加
name\u lenght
属性,每次保存
name
时计算它,在字段上添加索引并查询该字段。@muistooshort,(1)不正确…即使您不使用
^
启动模式,索引仍将被使用(请参阅Mongo关于的注释)。它指出,如果正则表达式是“前缀表达式”(例如,模式以
^
启动),则可能会进行进一步优化。(2)我还没有对这两个操作符进行基准测试,但是根据,它指出使用索引可以比集合扫描更快。
db.collection.find({ name: { $regex: /^.{7,14}$/ } })