Skip to main content

๐Ÿฆธ Advanced Exercises

info

Extra activity! Do it if you have extra time or are following along at home. These won't be covered during the hands-on lab.

Promote shorter booksโ€‹

You've noticed that readers tend to prefer shorter books. Without using a large score boost, try to promote shorter books in the search results.

tip

Even without a score adjuster, the should operator will still boost the score of the documents that match it.

Answer
public async searchBooks(query: string): Promise<Book[]> {
const aggregationPipeline = [
{
$search: {
"index": "fulltextsearch",
"compound": {
"must": [
{
"text": {
query,
"path": ["title", "authors.name", "genres"],
fuzzy: {
maxEdits: 2
}
}
}
],
"should": [
{
"equals": {
"value": true,
"path": "bookOfTheMonth",
"score": {
"boost": { value: 10 }
}
}
},
{
"range": {
path: "pages",
lt: 80
}
}
]
}
}
}
];
const books = await collections?.books?.aggregate(aggregationPipeline).toArray() as Book[];
return books;
}

Choose your favorite method to build aggregation pipelines and try to solve the following exercises.

Most available book of the month booksโ€‹

Build a search aggregation stage that will promote the books of the month and return the books with the most copies available first.

Most prolific pooh authorโ€‹

Find out which author has written the most books that contain the word "pooh" (we're talking about the bear here) in the title or synopsis.

Assume typos but still find the matchesโ€‹

Find books that match a user query, but also return books that match with a typo. These books should be returned after the books that match the query.