How to do a Full-Text Search in MongoDB using Mongoose
Last Updated :
21 Feb, 2025
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 our 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
Full-Text Search process enables searching for individual keywords, phrases, or even excluding terms from search results, making it ideal for applications that require fast and accurate text search capabilities. Below are the steps to set up and perform full-text search in MongoDB.
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 us to efficiently search for documents based on their text content. By enabling text indexing and understanding MongoDB's powerful text search capabilities, we can create robust search functionalities in our 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.
Similar Reads
How to Perform Text Search in MongoDB using Node.js?
MongoDB is an open-source, cross-platform, No-SQL database that stores data in documents, which contain data in the form of key-value pairs. In this article, we will learn about how to perform text-based searches in MongoDB using node.js. Prerequisites Node.jsMongoDBMongoDB Atlas Connect with Applic
5 min read
How to replace one document in MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Inst
1 min read
How to use MongoDB Projection in Mongoose?
MongoDB projection in Mongoose allows you to specify which fields to include or exclude in query results, optimizing data retrieval by returning only the necessary information from the database.Prerequisites:Nodejs NPMMongoDBJavaScriptThere are several ways to specify projection in Mongoose:Table of
4 min read
How To Query For Documents In MongoDB Using NodeJS?
MongoDB is the popular NoSQL database that allows for flexible and scalable data storage. NodeJS and JavaScript runtime built on Chrome's V8 JavaScript engine. It is often used with MongoDB to build powerful and efficient applications. In this article, we will guide you on how to query the documents
4 min read
How to add range in the Collection of Mongodb using Node.js ?
Mongoose.module is one of the most powerful external module of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server.Mongoose module provides several functions in order to manipulate the documen
2 min read
How to Use MongoDB and Mongoose with Node.js ?
MongoDB is a popular NoSQL database that offers flexibility and scalability, making it an excellent choice for modern applications. Mongoose, a powerful ODM (Object Data Modeling) library, simplifies the interaction between MongoDB and Node.js by providing a schema-based solution for data validation
6 min read
How to Define Schema and Model in Mongoose?
Mongoose is a widely used Object Data Modeling (ODM) library designed for MongoDB in Node.js applications It provides a straightforward way for interacting with MongoDB by offering a schema-based structure. In this article article, we will go through the process of defining schemas and models in Mon
6 min read
How to Perform a findOne Operation in MongoDB using Node.js?
The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fe
4 min read
How to set the document value type in MongoDB using Node.js?
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
MongoDB - Replace Documents Using MongoShell
MongoDB provides various methods to modify documents in a collection. One of the most important methods is replaceOne(), which allows you to replace an entire document with a new one based on a filter. This article will provide an in-depth explanation of how to replace documents in MongoDB using Mon
4 min read