For “like” implementation in MongoDB, use / / and set that specific letter in between. For example −
/J/
Let us create a collection with documents −
> db.demo554.insertOne({"UserName":"John","UserMailId":"[email protected]"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f1cfed1d72c4545cb8679") } > db.demo554.insertOne({"UserName":"Chris","UserMailId":"[email protected]"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f1d0cd1d72c4545cb867a") } > db.demo554.insertOne({"UserName":"Jace","UserMailId":"[email protected]"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f1d1cd1d72c4545cb867b") }
Display all documents from a collection with the help of find() method −
> db.demo554.find();
This will produce the following output −
{ "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "[email protected]" } { "_id" : ObjectId("5e8f1d0cd1d72c4545cb867a"), "UserName" : "Chris", "UserMailId" : "[email protected]" } { "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "[email protected]" }
Following is the query to implementation of “like” −
> db.demo554.find({ ... "$or": [ ... { "UserName": /J/ }, ... ... { "UserMailId": /J/ } ... ] ... } ... );
This will produce the following output −
{ "_id" : ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName" : "John", "UserMailId" : "[email protected]" } { "_id" : ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName" : "Jace", "UserMailId" : "[email protected]" }