To find which document contains a specific string, use $regex along with find(). Let us create a collection with documents −
> db.demo597.insertOne({"Name":"John Doe"});{ "acknowledged" : true, "insertedId" : ObjectId("5e947ae3f5f1e70e134e2690") } > db.demo597.insertOne({"Name":"John Smith"});{ "acknowledged" : true, "insertedId" : ObjectId("5e947ae8f5f1e70e134e2691") } > db.demo597.insertOne({"Name":"Chris Brown"});{ "acknowledged" : true, "insertedId" : ObjectId("5e947aeff5f1e70e134e2692") } > db.demo597.insertOne({"Name":"Adam Smith"});{ "acknowledged" : true, "insertedId" : ObjectId("5e947afff5f1e70e134e2693") }
Display all documents from a collection with the help of find() method −
> db.demo597.find();
This will produce the following output −
{ "_id" : ObjectId("5e947ae3f5f1e70e134e2690"), "Name" : "John Doe" } { "_id" : ObjectId("5e947ae8f5f1e70e134e2691"), "Name" : "John Smith" } { "_id" : ObjectId("5e947aeff5f1e70e134e2692"), "Name" : "Chris Brown" } { "_id" : ObjectId("5e947afff5f1e70e134e2693"), "Name" : "Adam Smith" }
Following is the query to find which MongoDB document contains a specific string −
> db.demo597.find({Name:{$regex:/smith/i}} );
This will produce the following output −
{ "_id" : ObjectId("5e947ae8f5f1e70e134e2691"), "Name" : "John Smith" } { "_id" : ObjectId("5e947afff5f1e70e134e2693"), "Name" : "Adam Smith" }