mangoose filter collection based on string match

Mongoose Filter Collection Based on String Match

Filtering a collection based on string match is a common requirement when working with databases. Mongoose is a popular Object Data Modeling (ODM) library for MongoDB in Node.js. In this post, we will explore how to filter a Mongoose collection based on string match.

Scenario

Imagine you have a collection of books, and you want to filter the books based on a search query entered by the user. The search query can be a title, author, or any other keyword.

Solution

The solution to this problem involves using the $regex operator in Mongoose. The $regex operator allows us to search for documents that match a regular expression pattern.

Let's assume that we have a Mongoose model for our books collection:


const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: String,
    required: true,
  },
  description: {
    type: String,
  },
});

const Book = mongoose.model('Book', bookSchema);

Now, let's say we want to filter the books based on a search query entered by the user:


const searchQuery = 'jungle';

const books = await Book.find({
  $or: [
    { title: { $regex: searchQuery, $options: 'i' } },
    { author: { $regex: searchQuery, $options: 'i' } },
    { description: { $regex: searchQuery, $options: 'i' } },
  ],
});

In the above code, we are using the $or operator to match any of the queries. We are also using the $options: 'i' flag to make the search case-insensitive. This means that the search will match the query regardless of its case.

If you want to filter based on a specific field, you can use the following code:


const searchQuery = 'jungle';

const books = await Book.find({
  title: { $regex: searchQuery, $options: 'i' },
});

In the above code, we are filtering based on the title field only.

Conclusion

Filtering a collection based on string match is a common requirement when working with databases. Mongoose makes it easy to filter collections based on regular expressions. In this post, we explored how to filter a Mongoose collection based on string match using the $regex operator. We also saw how to search for documents that match a regular expression pattern.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe