The data type of the field is String. I would like to fetch the data where character length of field name is greater than 40.
I tried these queries but returning error. 1.
db.usercollection.find(
{$where: "(this.name.length > 40)"}
).limit(2);
output :error: {
"$err" : "TypeError: Cannot read property 'length' of undefined near '40)' ",
"code" : 16722
}
this is working in 2.4.9 But my version is 2.6.5
Here is one of the way in mongodb you can achieve this.
I had a similar kind of scenario, but in my case string is not a 1st level attribute. It is inside an object. In here I couldn't find a suitable answer for it. So I thought to share my solution with you all(Hope this will help anyone with a similar kind of problem).
Ex: If we need to get only collections that having child's name's length is higher than 10 characters.
For MongoDB 3.6 and newer:
The
$expr
operator allows the use of aggregation expressions within the query language, thus you can leverage the use of$strLenCP
operator to check the length of the string as follows:For MongoDB 3.4 and newer:
You can also use the aggregation framework with the
$redact
pipeline operator that allows you to proccess the logical condition with the$cond
operator and uses the special operations$$KEEP
to "keep" the document where the logical condition is true or$$PRUNE
to "remove" the document where the condition was false.This operation is similar to having a
$project
pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent$match
, except that$redact
uses a single pipeline stage which is more efficient.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". Otherwise it is "pruned" and discarded.Consider running the following aggregate operation which demonstrates the above concept:
If using
$where
, try your query without the enclosing brackets:A better query would be to to check for the field's existence and then check the length:
or:
MongoDB evaluates non-
$where
query operations before$where
expressions and non-$where
query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying$where
will be much slower compared to that. It's recommended to use JavaScript expressions and the$where
operator as a last resort when you can't structure the data in any other way, or when you are dealing with a small subset of data.A different and faster approach that avoids the use of the
$where
operator is the$regex
operator. Consider the following pattern which searches forNote - From the docs: