Home »
MongoDB
Create regex to find documents with its initial characters in MongoDB
In this article, we are going to create the regex to find documents with its initial characters in MongoDB.
Submitted by Manu Jemini, on March 08, 2018
A record is a mongo document that is composed of field and value pairs. The documents are like JSON objects. Just like JSON in mongo we can put more documents inside a document.
$regex in MongoDB means expression capabilities for pattern matching strings, to find a document in MongoDB through an Express server we need to full fill certain requirements:
Read more in previous article: How to use $gt in MongoDB?
In the example below, we have to search for the matching string for company_name.
collection.find({company_name:{ $regex: /^f/ }}).
toArray(function(err,res){ })
Now, this function will result every matching company_name starting with f. Just like before we have to check for the error, if any. So to check if there is any error we use simple if-else statements.
Last thing is to check for error if any and to close the open connection that we made before by simply using method close().
JS file:
// require mongodb
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
//create url
var url = "mongodb://localhost:27017/vehicle";
//connect with mongo client
MongoClient.connect(url, function(err,db){
if(err)
{
console.log(err);
}
else
{
//console.log tthe connected url
console.log('Connected to ',url);
//get refernce of using collection
var collection = db.collection('cars');
// to find the documents
collection.find({company_name:{ $regex: /^f/ }}).toArray(function(err,res){
if(err)
{
console.log(err);
}else if(res.length)
{
console.log(res);
}else
{
console.log('No cars found');
}
db.close();
})
}
});
Output in console:
Output in shell: