
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Query MongoDB with Like Implementation on Name and Email Fields
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]" }
Advertisements