- 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
Search multiple fields for multiple values in MongoDB?
To search multiple fields for multiple values in MongoDB, you can use $text and $search operator. Let us first create a collection with documents
>db.searchMultipleFieldsDemo.insertOne({"_id":100,"FirstSubject":"Java","SecondSubject":"MongoDB"}); { "acknowledged" : true, "insertedId" : 100 } >db.searchMultipleFieldsDemo.insertOne({"_id":101,"FirstSubject":"MongoDB","SecondSubject":"MySQL"}); { "acknowledged" : true, "insertedId" : 101 } >db.searchMultipleFieldsDemo.insertOne({"_id":102,"FirstSubject":"MySQL","SecondSubject":"Java"}); { "acknowledged" : true, "insertedId" : 102 }
Following is the query to display all documents from a collection with the help of find() method
> db.searchMultipleFieldsDemo.find().pretty();
This will produce the following output
{ "_id" : 100, "FirstSubject" : "Java", "SecondSubject" : "MongoDB" } { "_id" : 101, "FirstSubject" : "MongoDB", "SecondSubject" : "MySQL" } { "_id" : 102, "FirstSubject" : "MySQL", "SecondSubject" : "Java" }
Following is the query to search multiple fields for multiple values in MongoDB
> db.searchMultipleFieldsDemo.find({"$text":{"$search":"Java MongoDB"}});
This will produce the following output
{ "_id" : 102, "FirstSubject" : "MySQL", "SecondSubject" : "Java" } { "_id" : 100, "FirstSubject" : "Java", "SecondSubject" : "MongoDB" } { "_id" : 101, "FirstSubject" : "MongoDB", "SecondSubject" : "MySQL" }
Advertisements