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
As for the logical condition, there are String Aggregation Operators that you can use $strLenCP operator to check the length of the string. If the length is $gt a specified value, then this is a true match and the document is "kept".
Yes, you can do that using $expr operator along with the $size operator. Here, we are using $expr operator to filter out all those documents which has size greater than or equal to 4.
The $size operator in MongoDB is used to fetch the document that has an array field of a specific size.
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)
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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With