Search for multiple words/substrings in a string using MongoDB Queries?

Viewed 156

I have a model as shown

[
    {"_id": "1", "Title": "boat test"},
    {"_id": "2", "Title": "mobiles and extras"}
]

Query_String = "boat" // should return [{"_id": "1", "Title": "boat test"}]

Query_String = "boat te" // should return [{"_id": "1", "Title": "boat test"}]

Query_String = "mobiles" // should return [{"_id": "2", "Title": "mobiles and extras"}]

Query_String = "mob" // should return [{"_id": "2", "Title": "mobiles and extras"}]

Query_String = "boat mobile" // should return [{"_id": "1", "Title": "boat test"}, {"_id": "2", "Title": "mobiles and extras"}]

My query is to get all products whose "Title" field has any of the words in a given Query_String

I tried this but this works for 1st case only in which Query_String is "boat"

const { Products } = require("../models/Products");

Products.find({
      Title: {
        $regex: `.*${Query_String}.*`,
        $options: "i",
      },
    })
1 Answers

There are 2 approaches,

Using javascript RegExp:

  • split string by space and make array, map to convert string to regular express
  • Try $in Expressions, To include a regular expression in an $in query expression, you can only use JavaScript regular expression objects (i.e. /pattern/ ). For example:
let QString = Query_String.split(" ").map(s => new RegExp(s));
Products.find({
  $or: [
    { Title: { $in: QString } },
    // more fields if needed
    { Category: { $in: QString } }
  ]  
});

Using $or conditional and $regex

  • split string by space and make array, map to prepare array of separate conditions
  • check $or condition
let QStringTitle = Query_String.split(" ").map(s => { 
  return {
    {
      Title: {
        $regex: s,
        $options: "i"
      }
    }
  };
});
let QStringCategory = Query_String.split(" ").map(s => { 
  return {
    {
      Category: {
        $regex: s,
        $options: "i"
      }
    }
  };
});
Products.find({ $or: QStringTitle.concat(QStringCategory) });
Related