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
Indexing large text field to make query faster in MongoDB
To index large text field, use ensureIndex() along with $regex for text search. Let us create a collection with documents −
> db.demo46.ensureIndex({"Name":1});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo46.insertOne({"Name":"John Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e267004cfb11e5c34d898ed")
}
> db.demo46.insertOne({"Name":"John Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e267009cfb11e5c34d898ee")
}
> db.demo46.insertOne({"Name":"Chris Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e267011cfb11e5c34d898ef")
}
Display all documents from a collection with the help of find() method −
> db.demo46.find();
This will produce the following output −
{ "_id" : ObjectId("5e267004cfb11e5c34d898ed"), "Name" : "John Smith" }
{ "_id" : ObjectId("5e267009cfb11e5c34d898ee"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e267011cfb11e5c34d898ef"), "Name" : "Chris Brown" }
Following is the query to index large text field to make query faster −
> db.demo46.find({ Name: { $regex:/^John/}});
This will produce the following output −
{ "_id" : ObjectId("5e267009cfb11e5c34d898ee"), "Name" : "John Doe" }
{ "_id" : ObjectId("5e267004cfb11e5c34d898ed"), "Name" : "John Smith" }Advertisements