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
Different approaches to performing text searches in MongoDB using Node.js:
Table of Content
- Using Index
- Exact Text Match
- Using Regular Expression
Step to create an application of NodeJs with Mongodb
Step 1: Create application using the following command:
npm init -y
Step 2: Install MongoDB by using the following command:
npm i mongodb
The updated dependency:
"dependencies": {
"mongodb": "^6.7.0"
}
Project Structure
Step 3: Database connection and Collection setup”
- Please refer to the MongoDB Atlas Connect with Application article or install the mongodb in local to get the connection URL.
- Then create a new collection and insert the following data:
[
{
"name": "John Doe",
"email": "john.doe@example.com",
"designation": "Software Engineer",
"gender": "Male"
},
{
"name": "Jane Smith",
"email": "jane.smith@example.com",
"designation": "Product Manager",
"gender": "Female"
},
{
"name": "Alice Johnson",
"email": "alice.johnson@example.com",
"designation": "UX Designer",
"gender": "Female"
},
{
"name": "Bob Brown",
"email": "bob.brown@example.com",
"designation": "Data Analyst",
"gender": "Male"
},
{
"name": "Charlie Davis",
"email": "charlie.davis@example.com",
"designation": "DevOps Engineer",
"gender": "Male"
},
{
"name": "Diana Prince",
"email": "diana.prince@example.com",
"designation": "Marketing Specialist",
"gender": "Female"
},
{
"name": "Eve Adams",
"email": "eve.adams@example.com",
"designation": "HR Manager",
"gender": "Female"
},
{
"name": "Frank Wilson",
"email": "frank.wilson@example.com",
"designation": "Sales Executive",
"gender": "Male"
},
{
"name": "Grace Hall",
"email": "grace.hall@example.com",
"designation": "Customer Support",
"gender": "Female"
},
{
"name": "Henry Clark",
"email": "henry.clark@example.com",
"designation": "Technical Writer",
"gender": "Male"
},
{
"name": "Ivy Lewis",
"email": "ivy.lewis@example.com",
"designation": "Project Manager",
"gender": "Female"
},
{
"name": "Jack White",
"email": "jack.white@example.com",
"designation": "QA Engineer",
"gender": "Male"
},
{
"name": "Kathy Turner",
"email": "kathy.turner@example.com",
"designation": "Content Strategist",
"gender": "Female"
},
{
"name": "Liam Harris",
"email": "liam.harris@example.com",
"designation": "Network Administrator",
"gender": "Male"
},
{
"name": "Mia Scott",
"email": "mia.scott@example.com",
"designation": "Business Analyst",
"gender": "Female"
},
{
"name": "Noah King",
"email": "noah.king@example.com",
"designation": "Full Stack Developer",
"gender": "Male"
},
{
"name": "Olivia Baker",
"email": "olivia.baker@example.com",
"designation": "Graphic Designer",
"gender": "Female"
},
{
"name": "Paul Martinez",
"email": "paul.martinez@example.com",
"designation": "Database Administrator",
"gender": "Male"
},
{
"name": "Quinn Rogers",
"email": "quinn.rogers@example.com",
"designation": "Operations Manager",
"gender": "Male"
},
{
"name": "Rachel Green",
"email": "rachel.green@example.com",
"designation": "Financial Analyst",
"gender": "Female"
}
]
Using Index
In this approach, we are going to use an Index. The index is a data structure that stores copies of parts of documents to run query more efficiently. Text index allows you to perform text searches on the contents of string fields in your documents.
Syntax
db.collection.createIndex({ "fieald1": "text", "fieald2": "text", "fieald3": "text".... })
db.collection.find({ $text: { $search: "searchText" } })
Example: This example shows the performance of text search using index search.
const { MongoClient } = require('mongodb');
// Replace uri with your actual connection string
const uri = "CONNECTION_URL";
const dbName = 'productDB';
// Function to connect to MongoDB
// Atlas and perform operations
async function connectToMongoDB() {
const client = new MongoClient(uri);
try {
// Connect to MongoDB Atlas
await client.connect();
console.log('Succesfully Connected to MongoDB Atlas');
// Access the database
const database = client.db(dbName);
// Access a collection
const collection = database.collection('products');
// Creating Index
await collection.createIndex({ "name": "text", "email": "text",
"designation": "text", "gender": "text" });
// Query the collection
const query = { $text: { $search: "@example" } }
const foundDocument = await collection.find(query).toArray();
console.log('Found document:', foundDocument);
} finally {
// Close the MongoDB Atlas connection
await client.close();
console.log('Connection to MongoDB Atlas closed');
}
}
// Calling connectToMongoDB function
connectToMongoDB();
Output:
Using find() method of MongoDB
In this approach, we have used a find() method of MongoDB. we are directly passing a whole text with field name that already exists in a database, we can also pass multiple fields for exact match.
Syntax
db.collection.find( { field1:"text", field2:"text".... } )
Example: This example shows the performance of text search using find() method of mongodb.
const { MongoClient } = require('mongodb');
// Replace uri with your actual connection string
const uri = "CONNECTION_URL";
const dbName = 'productDB';
// Function to connect to MongoDB Atlas and perform operations
async function connectToMongoDB() {
const client = new MongoClient(uri);
try {
// Connect to MongoDB Atlas
await client.connect();
console.log('Succesfully Connected to MongoDB Atlas');
// Access the database
const database = client.db(dbName);
// Access a collection
const collection = database.collection('products');
// Query the collection
const query = { name: "Jack White" }
const foundDocument = await collection.find(query).toArray();
console.log('Found document:', foundDocument);
} finally {
// Close the MongoDB Atlas connection
await client.close();
console.log('Connection to MongoDB Atlas closed');
}
}
// Calling connectToMongoDB function
connectToMongoDB();
Output:
Using Regular Expression
In this approach, we are going to use a find() function with regular expression to find a similar matching fields, We are using field specific regular expression, that will only search inside defined field.
Syntax
db.collection.find( { field: /searchText/i } )
Example: This example shows the performance of text search using regular expression.
const { MongoClient } = require('mongodb');
// Replace uri with your actual connection string
const uri = "CONNECTION_URL";
const dbName = 'productDB';
// Function to connect to MongoDB Atlas and perform operations
async function connectToMongoDB() {
const client = new MongoClient(uri);
try {
// Connect to MongoDB Atlas
await client.connect();
console.log('Succesfully Connected to MongoDB Atlas');
// Access the database
const database = client.db(dbName);
// Access a collection
const collection = database.collection('products');
// Query the collection
const query = { gender: /fe/i }
const foundDocument = await collection.find(query).toArray();
console.log('Found document:', foundDocument);
} finally {
// Close the MongoDB Atlas connection
await client.close();
console.log('Connection to MongoDB Atlas closed');
}
}
// Calling connectToMongoDB function
connectToMongoDB();
Output:
Contact Us