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
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
$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
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.
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
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
You can use a JavaScript expression.
User.where("this.name.length >= 7 && this.name.length <= 14")