Home > Software engineering >  Match exact string in mongoDB collection
Match exact string in mongoDB collection

Time:06-20

I have one collection in the MongoDB database, I want to fetch the mongo records whose title contains searched string only. Example:

Search String: iot

Result:

[{"title": "Probiotics"}, {"title": "Agricultural Biotechnology"}, {titie: "Global Aviation IoT Market - Forecast to 2024"}]

I am getting the above result, but I want similar to the following result:

[{titie: "Global Aviation IoT Market - Forecast to 2024"}].

I don't want first 2 elements in result, as its not matching the exact word with the search string.

I tried $regex for fetching the result.

ex:

const q = 'iot';
Reports.find({"title" : {$regex : q}}, {title:1}, (err, data) => {
          if(err) return res.status(500).send(e);
          return res.status(200).send({data});
});

CodePudding user response:

You need "\b" word boundary.

\b

Matches, without consuming any characters, immediately between a character matched by \w and a character not matched by \w (in either order). It cannot be used to separate non words from words.

Reference: Regex 101

Sample Regex 101 and Test Result

const q = "\\biot\\b"
db.collection.find({
  "title": {
    $regex: "\\biot\\b",
    $options: "i"
  }
},
{
  title: 1
})

Sample Mongo Playground

  • Related