- 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
Create an index for text search in MongoDB
Let us create a collection with documents −
> db.demo331.insertOne({"Words":"This is a MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e521c35f8647eb59e562089") } > db.demo331.insertOne({"Words":"THIS is a MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e521c36f8647eb59e56208a") }
Display all documents from a collection with the help of find() method−
> db.demo331.find();
This will produce the following output −
{ "_id" : ObjectId("5e521c35f8647eb59e562089"), "Words" : "This is a MySQL" } { "_id" : ObjectId("5e521c36f8647eb59e56208a"), "Words" : "THIS is a MongoDB" }
Following is the query to create an index for text search −
> db.demo331.createIndex( {Words: "text" } ); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo331.find({$text:{$search:"MySQL"}});
This will produce the following output −
{ "_id" : ObjectId("5e521c35f8647eb59e562089"), "Words" : "This is a MySQL" }
Advertisements