
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
Equivalent of SQL LIKE in MongoDB
You can use “$regex” operator to implement the equivalent of SQL ‘like’ in MongoDB. To implement it, let us create a collection with a document. The query to create a collection with a document is as follows −
> db.sqlLikeDemo.insertOne({"UserName":"John Smith","UserAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e124afe5c1d2279d6a5") } > db.sqlLikeDemo.insertOne({"UserName":"John Doe","UserAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e264afe5c1d2279d6a6") } > db.sqlLikeDemo.insertOne({"UserName":"Chris Williams","UserAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e404afe5c1d2279d6a7") } > db.sqlLikeDemo.insertOne({"UserName":"Robert Taylor","UserAge":26}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e4d4afe5c1d2279d6a8") } > db.sqlLikeDemo.insertOne({"UserName":"John Brown","UserAge":27}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e6c4afe5c1d2279d6a9") } > db.sqlLikeDemo.insertOne({"UserName":"Mike Brown","UserAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e794afe5c1d2279d6aa") } > db.sqlLikeDemo.insertOne({"UserName":"Larry Smith","UserAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5c912e8c4afe5c1d2279d6ab") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.sqlLikeDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c912e124afe5c1d2279d6a5"), "UserName" : "John Smith", "UserAge" : 24 } { "_id" : ObjectId("5c912e264afe5c1d2279d6a6"), "UserName" : "John Doe", "UserAge" : 21 } { "_id" : ObjectId("5c912e404afe5c1d2279d6a7"), "UserName" : "Chris Williams", "UserAge" : 22 } { "_id" : ObjectId("5c912e4d4afe5c1d2279d6a8"), "UserName" : "Robert Taylor", "UserAge" : 26 } { "_id" : ObjectId("5c912e6c4afe5c1d2279d6a9"), "UserName" : "John Brown", "UserAge" : 27 } { "_id" : ObjectId("5c912e794afe5c1d2279d6aa"), "UserName" : "Mike Brown", "UserAge" : 23 } { "_id" : ObjectId("5c912e8c4afe5c1d2279d6ab"), "UserName" : "Larry Smith", "UserAge" : 24 }
Here is the query that works like SQL ‘like’ clause i.e. the record with “UserName” John −
> db.sqlLikeDemo.find({"UserName":{"$regex": "John"}}).pretty();
The following is the output −
{ "_id" : ObjectId("5c912e124afe5c1d2279d6a5"), "UserName" : "John Smith", "UserAge" : 24 } { "_id" : ObjectId("5c912e264afe5c1d2279d6a6"), "UserName" : "John Doe", "UserAge" : 21 } { "_id" : ObjectId("5c912e6c4afe5c1d2279d6a9"), "UserName" : "John Brown", "UserAge" : 27 }
Advertisements