For full text search in MongoDB, use $text. The $text performs a text search on the content of the fields. Let us create a collection with documents −
> db.demo654.createIndex({Name:"text"}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo654.insertOne({"Name":"John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04e924deddd72997713c8") } > db.demo654.insertOne({"Name":"Chris Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04e9d4deddd72997713c9") } > db.demo654.insertOne({"Name":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04ea54deddd72997713ca") } > db.demo654.insertOne({"Name":"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea04eb24deddd72997713cb") }
Display all documents from a collection with the help of find() method −
> db.demo654.find();
This will produce the following output −
{ "_id" : ObjectId("5ea04e924deddd72997713c8"), "Name" : "John Doe" } { "_id" : ObjectId("5ea04e9d4deddd72997713c9"), "Name" : "Chris Brown" } { "_id" : ObjectId("5ea04ea54deddd72997713ca"), "Name" : "John Smith" } { "_id" : ObjectId("5ea04eb24deddd72997713cb"), "Name" : "David Miller" }
Following is the query to perform full text search in MongoDB −
> db.demo654.find({ $text: { $search: "John" } } );
This will produce the following output −
{ "_id" : ObjectId("5ea04ea54deddd72997713ca"), "Name" : "John Smith" } { "_id" : ObjectId("5ea04e924deddd72997713c8"), "Name" : "John Doe" }