Text Search in Aggregation Pipeline Example
In the following example, we are working with:
Database: gfg
Collection: people
Document: The people collection contains the five documents.
Example 1
In this example, we count the number of the document in which pet value is a cat:
Query:
db.people.aggregate([{$match:{$text:{$search:"Cat"}}},
{$group:{_id:null,total:{$sum:1}}}])
Output:
Example 2
In this example, we count the number of the document in which pet value is a dog:
Query:
db.people.aggregate([{$match:{$text:{$search:"Dog"}}},
{$group:{_id:null,total:{$sum:1}}}])
Output:
Example 3
In this example, we return the Sorted result by using text score. We return the result(all the documents that contain the specified text,i.e., “Dog”) in the sorted form using textScore
Query:
db.people.aggregate([{$match:{$text:{$search:"Dog"}}},
{$sort:{score:{$meta:"textScore"}}},
{$project:{_id:0,name:1}}])
Output:
MongoDB Text Search
MongoDB Text Search technique finds a piece of text or a specified word from the string fields. It enables users to search for specific words or phrases within text fields efficiently.
The text index and $text operator perform text search in MongoDB, providing a powerful way to search for textual data in MongoDB collections.
Contact Us