MongoDB Using $FIRST with Aggregation
Lets assume that MongoDB is being used as a data store for an e-commerce application(similar to Amazon.com) on which users can shop for and buy the items they desire.
All the users purchases are stored in a collection named ‘purchase_history’. Each document in the collection will be structured as below
The site also has a section on the page which displays the recent 5 categories associated with the products the users shopped.
For example if the user purchased 10 items of different categories in the following order :
sports kitchen sports furniture sports sports clothing jewellery sports shoes
The “Recent 5 categories” section with show the following data
sports kitchen furniture clothing jewellery
Logically thinking, we can achieve the above result if we do the following steps :
- Sort the data in the ‘purchase_history’ by ‘purchaseDate’ descending order so that the most recent purchase is at the top.
- Filter distinct values for the ‘categories’ in the sorted result of step #1.
- Extract the top 5 values.
The above can be achieved through Mongo query using Aggregation framework combined with Group and $FIRST.