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" }

Updated on: 01-Apr-2020

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements