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" }
Updated on: 2020-04-02T06:45:41+05:30

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements