Aggregation & Text Search in MongoDB

1. Introduction to Aggregation

Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and perform a variety of operations on the grouped data to return a single result. In SQL count(*) and with group by is an equivalent of MongoDB aggregation.

There are two stages of Aggregation

  • Match Stage: To filter our records which matches a criteria
  • Group Stage: To group up records by certain field

Both these stages are pipeline and are interchangeable.

1.1 Aggregate() method

Syntax:

>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

Example :
To return states with population above 10 Million from zip database

db.zips.aggregate(
 [
    { 
        $group: 
         { 
             _id: "$state", 
             totalPop: 
              { 
                  $sum: "$pop" 
              }
         }
    },
    {
         $match: { totalPop: { $gte: 10*1000*1000 } }
    }
 ] 
)

Here in aggregation pipeline, there is group followed by match.

2. Text Search

In MongoDB, a text search of string content is possible. To perform text search, MongoDB uses a text index and the $text operator.

Example:
To create a collection shop with the following documents:

db.stores.insert(
   [
     { _id: 1, name: "Bakes and shakes", description: "Milkshakes and cakes" },
     { _id: 2, name: "Buns and Bagels", description: "Bagels and hot dogs" },
     { _id: 3, name: "Coffee all day", description: "Just coffee" },
     { _id: 4, name: "Shop spree all day ", description: "Discounted clothing" },
     { _id: 5, name: "Spirit", description: "Ancient goods" }
   ]
)
  • Text Index: MongoDB provides text indexes to support text search queries on string content. Text indexes can include any field whose value is a string or an array of string elements. A collection can only have one text search index, but that index can cover multiple fields. For example: You can run the following in a mongo shell to allow text search over the name and description fields:
    db.stores.createIndex( { name: "text", description: "text" } )
  • $text Operator: The $text query operator performs text searches on a collection with a text index.For example: You could use the following query to find all shops containing any terms from the list “Buns”, “and”, and “Bagels”:
    db.stores.find( { $text: { $search: "Buns and Bagels" } } )
    • Exact Phrase: You can also search for exact phrases by wrapping them in double-quotes. For example: The following will find all documents containing “Buns” or “coffee”:
      b.stores.find( { $text: { $search: "Buns \"coffee\"" } } )
    • Term Exclusion: To exclude a word, you can append a “-” character. For example: To find all stores containing “all” or “day” but not “coffee”, use the following:
      db.stores.find( { $text: { $search: "all day -coffee" } } )