- 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
Implement Text search in MongoDB
For text search, you need to use $text along with $search. Let us create a collection with documents −
> db.demo156.createIndex({"StudentName":"text"}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo156.insertOne({"StudentName":"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3547e8fdf09dd6d08539e6") } > db.demo156.insertOne({"StudentName":"John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3547f2fdf09dd6d08539e7") } > db.demo156.insertOne({"StudentName":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3547f7fdf09dd6d08539e8") }
Display all documents from a collection with the help of find() method −
> db.demo156.find();
This will produce the following output −
{ "_id" : ObjectId("5e3547e8fdf09dd6d08539e6"), "StudentName" : "Chris Brown" } { "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" } { "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" }
Following is the query to implement text search in MongoDB −
> db.demo156.find({ $text: { $search: "John" } } )
This will produce the following output −
{ "_id" : ObjectId("5e3547f7fdf09dd6d08539e8"), "StudentName" : "John Smith" } { "_id" : ObjectId("5e3547f2fdf09dd6d08539e7"), "StudentName" : "John Doe" }
Advertisements