- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to query MongoDB with “like”?
You can easily query MongoDB with “like”:
db.yourCollectionName.find({"yourFieldName" : /.*yourMatchingValue.*/}).pretty();
To understand the above syntax, let us create a collection with some documents. Here, we have a collection with the name ‘employee’. The query is as follows:
> db.employee.insert({"EmployeeName":"John","EmployeeSalary":450000}); WriteResult({ "nInserted" : 1 }) > db.employee.insert({"EmployeeName":"Carol","EmployeeSalary":150000}); WriteResult({ "nInserted" : 1 }) > db.employee.insert({"EmployeeName":"James","EmployeeSalary":550000}); WriteResult({ "nInserted" : 1 }) > db.employee.insert({"EmployeeName":"Jace","EmployeeSalary":670000}); WriteResult({ "nInserted" : 1 }) > db.employee.insert({"EmployeeName":"Larry","EmployeeSalary":1000000}); WriteResult({ "nInserted" : 1 })
Now you can display all documents from a collection using find() method. The query is as follows:
> db.employee.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6c0b2e68174aae23f5ef59"), "EmployeeName" : "John", "EmployeeSalary" : 450000 } { "_id" : ObjectId("5c6c0b3b68174aae23f5ef5a"), "EmployeeName" : "Carol", "EmployeeSalary" : 150000 } { "_id" : ObjectId("5c6c0b4768174aae23f5ef5b"), "EmployeeName" : "James", "EmployeeSalary" : 550000 } { "_id" : ObjectId("5c6c0b8f68174aae23f5ef5c"), "EmployeeName" : "Jace", "EmployeeSalary" : 670000 } { "_id" : ObjectId("5c6c0b9e68174aae23f5ef5d"), "EmployeeName" : "Larry", "EmployeeSalary" : 1000000 }
Here is the query in MongoDB with “like” operator:
> db.employee.find({"EmployeeName":/.*J.*/}).pretty();
The following is the output:
{ "_id" : ObjectId("5c6c0b2e68174aae23f5ef59"), "EmployeeName" : "John", "EmployeeSalary" : 450000 } { "_id" : ObjectId("5c6c0b4768174aae23f5ef5b"), "EmployeeName" : "James", "EmployeeSalary" : 550000 } { "_id" : ObjectId("5c6c0b8f68174aae23f5ef5c"), "EmployeeName" : "Jace", "EmployeeSalary" : 670000 }
Advertisements