How to perform a full-text search in MongoDB and Mongoose and JavaScript?

Estimated read time 2 min read

To perform a full-text search in MongoDB and Mongoose, you can use the built-in text search feature. Here’s an example of how to do it in JavaScript:

First, create a Mongoose model that supports text indexing. For example, a Product model with a name field that you want to search:

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    index: true, // enable text indexing for this field
  },
  description: String,
  price: Number,
});

const Product = mongoose.model('Product', productSchema);

Next, create a text index on the name field:

Product.createIndexes({ name: 'text' });

Then, perform a full-text search using the $text operator and the find() method:

Product.find({ $text: { $search: 'red shoes' } }, (err, products) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(products);
});

In the above example, we use the $text operator with the $search parameter to perform a full-text search for the phrase “red shoes”. This will return all documents in the Product collection that contain the words “red” and “shoes” in the name field.

Note that full-text search requires a text index on the collection and may not be suitable for all use cases. Full-text search can be slow for large collections and may not provide the same level of precision as other search techniques. Additionally, text indexes can take up a significant amount of space on disk, so you should only enable text indexing for fields that you actually need to search.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply