Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query MongoDB with length criteria

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

like image 814
Dogbert Avatar asked Feb 09 '11 21:02

Dogbert


People also ask

How do I get the length of a field in MongoDB?

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

Is there a way to query array fields with size greater than some specified value?

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.

How do I find the length of an array in MongoDB?

The $size operator in MongoDB is used to fetch the document that has an array field of a specific size.


2 Answers

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

like image 78
galenandrew Avatar answered Sep 24 '22 19:09

galenandrew


You can use a JavaScript expression.

User.where("this.name.length >= 7 && this.name.length <= 14")
like image 33
Simone Carletti Avatar answered Sep 22 '22 19:09

Simone Carletti