Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB Regex Search on Integer Value?
To perform Regex search on integer value, you need to use $where operator. The syntax is as follows:
db.yourCollectionName.find({ $where:
"/^yourIntegerPatternValue.*/.test(this.yourFieldName)" });
To understand the above concept, let us create a collection with document. The query to create a collection with document is as follows:
> db.regExpOnIntegerDemo.insertOne({"StudentId":2341234});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70370c75eb1743ddddce21")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":123234});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70371175eb1743ddddce22")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":9871234});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70371875eb1743ddddce23")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":2345612});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70372275eb1743ddddce24")
}
> db.regExpOnIntegerDemo.insertOne({"StudentId":1239812345});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c70372975eb1743ddddce25")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.regExpOnIntegerDemo.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c70370c75eb1743ddddce21"), "StudentId" : 2341234 }
{ "_id" : ObjectId("5c70371175eb1743ddddce22"), "StudentId" : 123234 }
{ "_id" : ObjectId("5c70371875eb1743ddddce23"), "StudentId" : 9871234 }
{ "_id" : ObjectId("5c70372275eb1743ddddce24"), "StudentId" : 2345612 }
{ "_id" : ObjectId("5c70372975eb1743ddddce25"), "StudentId" : 1239812345 }
Here is the query to do Regex search on integer value:
> db.regExpOnIntegerDemo.find({ $where: "/^123.*/.test(this.StudentId)" });
The following is the output:
{ "_id" : ObjectId("5c70371175eb1743ddddce22"), "StudentId" : 123234 }
{ "_id" : ObjectId("5c70372975eb1743ddddce25"), "StudentId" : 1239812345 }Advertisements