Query MongoDB with length criteria

2019-02-06 05:51发布

问题:

I have several documents in a MongoDB Collection, with a field 'name' (which is a String).

How can I perform queries like 7 <= name.length <= 14

回答1:

You can use a JavaScript expression.

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


回答2:

Mongo provides a few ways to perform a query with length criteria – $where or $regex are two great options however I would recommend using $regex due to better query performance.


$where (slower)

Accepts either a JavaScript expression or function in queries

Example:

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

Note: The $where operator will not take advantage of your database indexes, resulting in a much slower query. - Source


$regex (faster)

Provides regular expression capabilities for pattern matching strings in queries

Example:

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

Note: The $regex operator will take advantage of your database indexes, resulting in a much faster query (if your collection is indexed properly). - Source



回答3:

You can use MongoDB's $where query parameter to submit javascript to the server. E.g.,:

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



回答4:

$where queries are not very efficient. MongoDB

If this is a frequently executed query, you might want to store the length in a separate field. Denormalization