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
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