使用长度标准查询MongoDB

我在MongoDB集合中有几个文档,带有字段’name’(这是一个String)。

如何执行7 <= name.length <= 14

您可以使用JavaScript表达式 。

 User.where("this.name.length >= 7 && this.name.length <= 14") 

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


$where (慢)

在查询中接受JavaScript表达式或函数

例:

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

注意: $where运算符不会利用您的数据库索引,从而导致查询速度变慢。 - 来源


$regex (更快)

为查询中的模式匹配字符串提供正则表达式function

例:

 db.collection.find({ name: { $regex: /^.{7,14}$/ } }) 

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

您可以使用MongoDB的$ where查询参数将javascript提交给服务器。 例如,:

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

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D

$where查询效率不高。 MongoDB的

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