Mongoose: Find Documents That Contain a Given String

Updated: December 30, 2023 By: Guest Contributor Post a comment

Overview

This tutorial dives into the versatile querying capabilities of Mongoose, demonstrating how to effectively find documents within a MongoDB collection that contain a specific string. We’ll explore multiple approaches with code examples, leveraging the power of Mongoose and the latest JavaScript features.

Before you begin, ensure that you have the following setup on your local development environment:

  • Node.js installed
  • A MongoDB database accessible
  • Mongoose/npm package integrated into your project

Basic String Search

Let’s start with a basic search to find documents where a field exactly matches a given string.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const YourSchema = new Schema({
    fieldName: String,
});

const YourModel = mongoose.model('YourModel', YourSchema);

async function findExactMatch() {
    const result = await YourModel.find({ fieldName: 'YourString' }).exec();
    return result;
}

findExactMatch().then(docs => console.log(docs));

Case-Insensitive String Search

Now we step into performing a case-insensitive search where the casing of the string should not affect our search results.

/* ... */

async function findCaseInsensitive() {
    const query = { fieldName: new RegExp('yourstring', 'i') };
    const result = await YourModel.find(query).exec();
    return result;
}

findCaseInsensitive().then(docs => console.log(docs));

Partial String Search

If you need to find documents that contain a string within a field, not just an exact match, we utilize regular expressions.

/* ... */

async function findPartialMatch() {
    const query = { fieldName: /.*YourString.*/i };
    const result = await YourModel.find(query).exec();
    return result;
}

findPartialMatch().then(docs => console.log(docs));

Text Indexing and Search

In this section, we cover how to perform a full text search across multiple fields using text indexes.

/* ... */

YourSchema.index({ fieldName1: 'text', fieldName2: 'text' });

async function fullTextSearch() {
    const result = await YourModel.find({ $text: { $search: '"YourString"' } }, { score: { $meta: 'textScore' } }).sort({ score: { $meta: 'textScore' } }).exec();
    return result;
}

fullTextSearch().then(docs => console.log(docs));

Using Aggregation for Advanced String Search

For complex string queries, MongoDB’s aggregation framework offers more sophistication and flexibility. Here we show an advance use-case where we match and project fields in our documents.

/* ... */

async function advancedStringSearch() {
    const pipeline = [
        { $match: { fieldName: /.*YourString.*/i } },
        { $project: { fieldName: 1, _id: 0 } }
    ];
    const result = await YourModel.aggregate(pipeline).exec();
    return result;
}

advancedStringSearch().then(docs => console.log(docs));

Handling Special Characters and Escaping RegEx

Dealing with special characters in strings requires that they be escaped correctly before attempting a RegEx search.

/* ... */

// Function to escape special characters in a string for use in a regular expression
function escapeRegex(string) {
    // The replace function escapes special characters by adding a backslash before them
    return string.replace(/[-\^$*+?.()|[\]{}]/g, '\\$&');
}

// Asynchronous function to find documents with special characters in a field
async function findSpecialChars() {
    // Escape special characters in the input string
    const escapedString = escapeRegex('YourString?');

    // Create a case-insensitive regular expression query
    const query = { fieldName: new RegExp(escapedString, 'i') };

    // Execute the query and wait for the result
    const result = await YourModel.find(query).exec();

    // Return the result
    return result;
}

// Call the function and log the documents found
findSpecialChars().then(docs => console.log(docs));

This code escapes special characters in a string, constructs a case-insensitive regular expression query with the escaped string, and finds documents in a Mongoose model where a field matches the query. The documents found are then logged to the console.

Summary

In this tutorial, we’ve explored various techniques for finding documents containing a specific string in MongoDB using Mongoose. From basic exact matches to more advanced text searches with complex requirements, you now have the tools to query your collections efficiently and effectively.