Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find Strings greater than a particular length in MongoDB?
To find strings with a length greater than a particular value in MongoDB, use the $where operator with JavaScript expressions to access the string's length property.
Syntax
db.collectionName.find({
$where: 'this.fieldName.length > value'
});
Sample Data
Let us create a collection with user documents to demonstrate string length filtering ?
db.stringFieldLengthDemo.insertMany([
{"UserId": 1, "UserName": "Adam Smith"},
{"UserId": 2, "UserName": "Carol Taylor"},
{"UserId": 3, "UserName": "James Brown"},
{"UserId": 4, "UserName": "John Smith"},
{"UserId": 5, "UserName": "David Miller"},
{"UserId": 6, "UserName": "John Williams"},
{"UserId": 7, "UserName": "Chris Evans"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c77bb4b2386c62d05142a78"),
ObjectId("5c77bb562386c62d05142a79"),
ObjectId("5c77bb5b2386c62d05142a7a"),
ObjectId("5c77bb662386c62d05142a7b"),
ObjectId("5c77bb892386c62d05142a7c"),
ObjectId("5c77bbb02386c62d05142a7d"),
ObjectId("5c77bbd32386c62d05142a7e")
]
}
Display All Documents
db.stringFieldLengthDemo.find();
{
"_id": ObjectId("5c77bb4b2386c62d05142a78"),
"UserId": 1,
"UserName": "Adam Smith"
}
{
"_id": ObjectId("5c77bb562386c62d05142a79"),
"UserId": 2,
"UserName": "Carol Taylor"
}
{
"_id": ObjectId("5c77bb5b2386c62d05142a7a"),
"UserId": 3,
"UserName": "James Brown"
}
{
"_id": ObjectId("5c77bb662386c62d05142a7b"),
"UserId": 4,
"UserName": "John Smith"
}
{
"_id": ObjectId("5c77bb892386c62d05142a7c"),
"UserId": 5,
"UserName": "David Miller"
}
{
"_id": ObjectId("5c77bbb02386c62d05142a7d"),
"UserId": 6,
"UserName": "John Williams"
}
{
"_id": ObjectId("5c77bbd32386c62d05142a7e"),
"UserId": 7,
"UserName": "Chris Evans"
}
Example: Find Strings Longer Than 11 Characters
Query to find usernames with more than 11 characters ?
db.stringFieldLengthDemo.find({
$where: 'this.UserName.length > 11'
});
{
"_id": ObjectId("5c77bb562386c62d05142a79"),
"UserId": 2,
"UserName": "Carol Taylor"
}
{
"_id": ObjectId("5c77bb892386c62d05142a7c"),
"UserId": 5,
"UserName": "David Miller"
}
{
"_id": ObjectId("5c77bbb02386c62d05142a7d"),
"UserId": 6,
"UserName": "John Williams"
}
Key Points
- The
$whereoperator executes JavaScript expressions on each document - Use
this.fieldName.lengthto access the string length property - This method is slower than indexed queries, so use sparingly on large collections
Conclusion
The $where operator with JavaScript expressions provides a flexible way to filter documents based on string length. While powerful, consider performance implications for large datasets.
Advertisements
