To find documents containing a particular value with Regular Expressions, use MongoDB $regex. Let us create a collection with documents −
> db.demo469.insertOne({"StudentName":"John Doe"});{ "acknowledged" : true, "insertedId" : ObjectId("5e80532fb0f3fa88e227906b") } > db.demo469.insertOne({"StudentName":"Chris Brown"});{ "acknowledged" : true, "insertedId" : ObjectId("5e80533ab0f3fa88e227906c") } > db.demo469.insertOne({"StudentName":"John Smith"});{ "acknowledged" : true, "insertedId" : ObjectId("5e805341b0f3fa88e227906d") } > db.demo469.insertOne({"StudentName":"Jace Doe"});{ "acknowledged" : true, "insertedId" : ObjectId("5e805347b0f3fa88e227906e") } > db.demo469.insertOne({"StudentName":"David Miller"});{ "acknowledged" : true, "insertedId" : ObjectId("5e80534eb0f3fa88e227906f") }
Display all documents from a collection with the help of find() method −
> db.demo469.find();
This will produce the following output −
{ "_id" : ObjectId("5e80532fb0f3fa88e227906b"), "StudentName" : "John Doe" } { "_id" : ObjectId("5e80533ab0f3fa88e227906c"), "StudentName" : "Chris Brown" } { "_id" : ObjectId("5e805341b0f3fa88e227906d"), "StudentName" : "John Smith" } { "_id" : ObjectId("5e805347b0f3fa88e227906e"), "StudentName" : "Jace Doe" } { "_id" : ObjectId("5e80534eb0f3fa88e227906f"), "StudentName" : "David Miller" }
Following is the query to find documents which contain a particular value in MongoDB −
> db.demo469.find({'StudentName': {'$regex':'john', '$options':'i'}});
This will produce the following output −
{ "_id" : ObjectId("5e80532fb0f3fa88e227906b"), "StudentName" : "John Doe" } { "_id" : ObjectId("5e805341b0f3fa88e227906d"), "StudentName" : "John Smith" }