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
How to retrieve the documents whose values end with a particular character in MongoDB?
To retrieve documents whose field values end with a particular character in MongoDB, use the $regex operator with the dollar sign ($) anchor to match the end of the string.
Syntax
db.collection.find({
fieldName: { $regex: "character$" }
});
The $ symbol ensures the pattern matches only at the end of the string.
Sample Data
Let us create a collection with sample documents ?
db.students.insertMany([
{ "StudentName": "Adam", "StudentAge": 25, "StudentCountryName": "LAOS" },
{ "StudentName": "Sam", "StudentAge": 24, "StudentCountryName": "ANGOLA" },
{ "StudentName": "Robert", "StudentAge": 21, "StudentCountryName": "AUS" },
{ "StudentName": "Chris", "StudentAge": 20, "StudentCountryName": "UK" },
{ "StudentName": "Larry", "StudentAge": 23, "StudentCountryName": "US" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9c45b32d66697741252456"),
ObjectId("5c9c45c02d66697741252457"),
ObjectId("5c9c45cb2d66697741252458"),
ObjectId("5c9c45d92d66697741252459"),
ObjectId("5c9c45eb2d6669774125245a")
]
}
Example: Find Countries Ending with "S"
To retrieve documents where StudentCountryName ends with the character "S" ?
db.students.find({
StudentCountryName: { $regex: "S$" }
}).pretty();
{
"_id": ObjectId("5c9c45b32d66697741252456"),
"StudentName": "Adam",
"StudentAge": 25,
"StudentCountryName": "LAOS"
}
{
"_id": ObjectId("5c9c45cb2d66697741252458"),
"StudentName": "Robert",
"StudentAge": 21,
"StudentCountryName": "AUS"
}
{
"_id": ObjectId("5c9c45eb2d6669774125245a"),
"StudentName": "Larry",
"StudentAge": 23,
"StudentCountryName": "US"
}
Key Points
- The
$anchor matches the end of the string - Use
^anchor to match the beginning of strings - Regular expressions are case-sensitive by default
- Add
"i"option for case-insensitive matching:{ $regex: "s$", $options: "i" }
Conclusion
The $regex operator with the $ anchor provides an efficient way to find documents where field values end with specific characters. This pattern matching technique is essential for text-based queries in MongoDB.
Advertisements
