![]() |
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
PrerequisitesBefore we learn about performing a full-text search with Mongoose, We must ensure that we have the following set up:
Setting up MongooseBefore 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', { Replace ‘mongodb://localhost:27017/mydb’ with our MongoDB connection string. Defining Mongoose SchemaDefine a Mongoose schema to represent the structure of your MongoDB documents const articleSchema = new mongoose.Schema({ In this example, we’ve defined a schema for articles containing title and content fields. Steps to Perform Full-Text SearchStep 1:Preparing the Test DataLet’s assume we have the following articles stored in our MongoDB collection: [ Step 2: Creating a Text IndexTo 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 WordsPerform a full-text search to find articles containing specific keywords: async function searchText(query) { Output for searching ‘MongoDB’: [ Step 4: Searching for Full Phrases and Using ExclusionsSearch for full phrases or exclude certain terms from your search: // Searching for a full phrase Output for searching ‘”Using Mongoose”‘: [ Output for excluding ‘Mongoose’: [ ConclusionOverall, 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. |
Reffered: https://www.geeksforgeeks.org
Databases |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |