Mongo full text search example

Project: codever - File: personal-bookmarks-search.service.js

To perform a text search query on the text index of a collection, you need to use the $text operator. In the example below the results are sorted in order of relevance score, which you must explicitly project to the $meta textScore field and sort on it:

let getPersonalBookmarksForSearchedTerms = async function (nonSpecialSearchTerms, page, limit, userId, specialSearchFilters, searchInclude) {

  let filter = {userId: userId};
  if ( nonSpecialSearchTerms.length > 0 ) {
    if ( searchInclude === 'any' ) {
      filter.$text = {$search: nonSpecialSearchTerms.join(' ')}
    } else {
      filter.$text = {$search: bookmarksSearchHelper.generateFullSearchText(nonSpecialSearchTerms)};
    }
  }
  addSpecialSearchFiltersToMongoFilter(specialSearchFilters, filter);

  let bookmarks = await Bookmark.find(
    filter,
    {
      score: {$meta: "textScore"}
    }
  )
    .sort({score: {$meta: "textScore"}})
    .skip((page - 1) * limit)
    .limit(limit)
    .lean()
    .exec();

  return bookmarks;
}

By default, the full text search in Mongo looks for any of the terms, so a query of “java exception” will look for the bookmarks that container java or exception. You can force an AND search by using the terms in double quotes, so the query text would be "java" "exception". This is what the following generateFullSearchText function does for terms that you do not want excluded (To exclude a word in mongo, you can prepend a “-” character):

let generateFullSearchText = function (nonSpecialSearchTerms) {
  let termsQuery = '';
  nonSpecialSearchTerms.forEach(searchTerm => {
    if ( searchTerm.startsWith('-') ) {
      termsQuery += ' ' + searchTerm;
    } else { //wrap it in quotes to make it a default AND in search
      termsQuery += ' "' + searchTerm.substring(0, searchTerm.length) + '"';
    }
  });

  return termsQuery.trim();
};

Reference - https://docs.mongodb.com/manual/text-search/


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

routerLink with query params in Angular html template

routerLink with query params in Angular html template code snippet Continue reading