Open In App

How to do a Full-Text Search in MongoDB using Mongoose

Last Updated : 24 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In MongoDB, performing a full-text search allows us to query and retrieve documents based on textual content matching certain criteria. When using Mongoose, an ODM (Object Data Modeling) library for MongoDB in Node.js, conducting full-text search operations can be efficiently achieved using the MongoDB text search capabilities. In this article, we’ll explore how to perform a full-text search in MongoDB using Mongoose, covering concepts, examples, and outputs to help beginners grasp the process effectively.

Understanding Full-Text Search

  • Full-text search in MongoDB enables us to search for documents based on the text content of one or more fields.
  • Unlike traditional exact match queries, full-text search allows for partial matches and provides relevance scoring and making it ideal for searching text-heavy fields such as descriptions, comments, or articles.
  • Stemming is the process of reducing words to their root form (e.g., “running” to “run”). MongoDB’s full-text search supports language-specific stemming for more accurate results.
  • Full-text search typically excludes common words (stop words) like “and,” “or,” and “the” from indexing to improve performance and relevance.

Prerequisites

Before we learn about performing a full-text search with Mongoose, We must ensure that we have the following set up:

  • Node.js is installed on our machine.
  • MongoDB server running locally or remotely.
  • Basic understanding of JavaScript and MongoDB.

Setting up Mongoose

Before we perform the full-text search, let’s ensure that we have Mongoose set up in our Node.js project. We can install Mongoose via npm:

npm install mongoose

Once installed, require Mongoose in our Node.js application

const mongoose = require('mongoose');

Connect to our MongoDB database using Mongoose

mongoose.connect('mongodb://localhost:27017/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true
});

Replace ‘mongodb://localhost:27017/mydb’ with our MongoDB connection string.

Defining Mongoose Schema

Define a Mongoose schema to represent the structure of your MongoDB documents

const articleSchema = new mongoose.Schema({
title: String,
content: String
});

const Article = mongoose.model('Article', articleSchema);

In this example, we’ve defined a schema for articles containing title and content fields.

Steps to Perform Full-Text Search

Step 1:Preparing the Test Data

Let’s assume we have the following articles stored in our MongoDB collection:

[
{ "_id": "1", "title": "Introduction to MongoDB", "content": "MongoDB is a NoSQL database." },
{ "_id": "2", "title": "MongoDB Tutorial", "content": "Learn MongoDB basics with examples." },
{ "_id": "3", "title": "Using Mongoose with MongoDB", "content": "Mongoose simplifies MongoDB interactions in Node.js." }
]

Step 2: Creating a Text Index

To enable efficient full-text searches, create a text index on specific fields (title and content) within our MongoDB collection:

articleSchema.index({ title: 'text', content: 'text' });

Step 3: Searching for One or More Individual Words

Perform a full-text search to find articles containing specific keywords:

async function searchText(query) {
try {
const results = await Article.find({ $text: { $search: query } });
return results;
} catch (error) {
console.error('Error searching articles:', error);
throw error;
}
}

// Example usage:
searchText('MongoDB').then((articles) => {
console.log('Search results:', articles);
}).catch((error) => {
console.error('Search failed:', error);
});

Output for searching ‘MongoDB’:

[
{ "_id": "1", "title": "Introduction to MongoDB", "content": "MongoDB is a NoSQL database." },
{ "_id": "2", "title": "MongoDB Tutorial", "content": "Learn MongoDB basics with examples." },
{ "_id": "3", "title": "Using Mongoose with MongoDB", "content": "Mongoose simplifies MongoDB interactions in Node.js." }
]

Step 4: Searching for Full Phrases and Using Exclusions

Search for full phrases or exclude certain terms from your search:

// Searching for a full phrase
searchText('"Using Mongoose"').then((articles) => {
console.log('Search results:', articles);
}).catch((error) => {
console.error('Search failed:', error);
});

// Excluding a term
searchText('MongoDB -Mongoose').then((articles) => {
console.log('Search results:', articles);
}).catch((error) => {
console.error('Search failed:', error);
});

Output for searching ‘”Using Mongoose”‘:

[
{ "_id": "3", "title": "Using Mongoose with MongoDB", "content": "Mongoose simplifies MongoDB interactions in Node.js." }
]

Output for excluding ‘Mongoose’:

[
{ "_id": "1", "title": "Introduction to MongoDB", "content": "MongoDB is a NoSQL database." },
{ "_id": "2", "title": "MongoDB Tutorial", "content": "Learn MongoDB basics with examples." }
]

Conclusion

Overall, Performing a full-text search in MongoDB using Mongoose allows you to efficiently search for documents based on their text content. By enabling text indexing and understanding MongoDB’s powerful text search capabilities, you can create robust search functionalities in your Node.js applications. In this article, we covered the process of setting up Mongoose, defining schemas, enabling text indexing, and performing full-text search queries with examples and outputs.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads