Sling Academy
Home/Node.js/Mongoose: Find Documents That Contain a Given String

Mongoose: Find Documents That Contain a Given String

Last updated: December 30, 2023

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

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));

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));

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));

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));

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.

Next Article: Mongoose: Search documents by keywords (text search)

Previous Article: Mongoose: Find documents since last day, last week, last month

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates