Sling Academy
Home/Node.js/Using Regular Expressions in Mongoose Queries

Using Regular Expressions in Mongoose Queries

Last updated: December 31, 2023

Regular Expressions are powerful tools in MongoDB and Mongoose for performing flexible searches. This article guides you through their application in Mongoose queries with practical examples.

Getting Started with Mongoose and Regex

Before diving into regular expressions, ensure that you have Mongoose installed and connected to your MongoDB database. The examples in this tutorial will build on this foundation.

Basic Filter with Regex

const result = await Model.find({ name: /john/i });

The example shows a basic case-insensitive search for documents where the ‘name’ field contains ‘john’.

Creating a Mongoose Schema

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  name: String
});

const User = mongoose.model('User', userSchema);

We’ll be performing queries on a simple User schema.

Basic Regular Expression Queries

Begin with straightforward regex patterns to search for substrings within fields of your documents.

Simple Contains Query

const containsJohn = await User.find({ name: /john/i });

Search for any occurrence of ‘john’ regardless of case.

Exact Match Query

const exactMatch = await User.find({ name: /^John$/ });

The caret (^) and dollar sign ($) are anchors that represent the beginning and end of the line, respectively.

Advanced Regex Patterns

As you grow more comfortable with regex, you can utilize more powerful patterns to refine your searches.

Wildcard Searches

const wildcardSearch = await User.find({ name: /^Jo.*n$/i });

Finds names starting with ‘Jo’ and ending in ‘n’, with any characters in between.

Optional Characters

const optionalChars = await User.find({ name: /Joh?n/i });

Finds ‘John’ or ‘Jon’ by making the ‘h’ optional.

Escaping Special Characters

const escapingChars = await User.find({ name: /Jo\.n/i });

Searches for ‘Jo.n’ where the dot is treated as a literal dot, not a wildcard character.

Combining Regex with Other Query Operators

Mongoose allows you to integrate regex with its query operators to create complex queries.

Using $or Operator with Regex

const orOperator = await User.find({ $or: [{ name: /john/i }, { name: /jane/i }] });

Returns users with a name containing either ‘john’ or ‘jane’.

Using $and Operator with Regex

const andOperator = await User.find({ $and: [{ name: /^J/ }, { name: /n$/ }] });

The query selects records where ‘name’ starts with ‘J’ and ends with ‘n’.

Indexing for Optimized Searches

When using regex in queries, appropriate indexing can improve search performance significantly.

userSchema.index({ name: 'text' });

Adding a text index to the ‘name’ field can help speed up certain regex searches.

Regex Performance Considerations

Understand the impact of using regular expressions on the performance of your queries and ways to optimize.

Start of String Anchored Expressions

const anchoredSearch = await User.find({ name: /^Jo/ });

Anchoring an expression to the start of a string is far more efficient than otherwise.

Avoid Leading Wildcards

const efficientSearch = await User.find({ name: /hn$/ });

Leading wildcards can make the search slower, so use them judiciously.

Conclusion

Regular expressions unlock a wide range of search capabilities in Mongoose. Their proper use adds incredible flexibility to data queries while ensuring efficiency with appropriate practices and indexing.

Next Article: Fix mongoError: Topology was destroyed – Mongoose

Previous Article: Mongoose: How to push object to an array in a document

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