For text search in MongoDB with Regular Expression, use $regex. Let us create a collection with documents −
> db.demo519.insertOne({"Value":"50,60,70"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e88b9c0b3fbf26334ef6111")
}
> db.demo519.insertOne({"Value":"80,90,50"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e88b9c7b3fbf26334ef6112")
}
> db.demo519.insertOne({"Value":"10,30,40"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e88b9cfb3fbf26334ef6113")
}Display all documents from a collection with the help of find() method −
> db.demo519.find();
This will produce the following output −
{ "_id" : ObjectId("5e88b9c0b3fbf26334ef6111"), "Value" : "50,60,70" }
{ "_id" : ObjectId("5e88b9c7b3fbf26334ef6112"), "Value" : "80,90,50" }
{ "_id" : ObjectId("5e88b9cfb3fbf26334ef6113"), "Value" : "10,30,40" }Following is the query to implement text search in MongoDB with Regex −
> db.demo519.findOne({ Value: { $regex: /50/ } });This will produce the following output −
{ "_id" : ObjectId("5e88b9c0b3fbf26334ef6111"), "Value" : "50,60,70" }