Tronathan
Tronathan

Reputation: 6784

How to find matches that occur within a specified string with regex?

I have a unique situation where I need to query a mongo database to find the names of people who occur in a body of text. The query must specify the body of text and find records with values that occur in the body of text. How can I do this with a regular expression?

I need to write a query where this would match: /Jonathan is a handsome guy/.test('Jonathan')

The problem is that the text inside "test" is the value of a mongo field, so this query must be written such that the body of text is provided as input, and it matches on names that occur within (are substrings of) the body of text.

A more concrete example:

db.test.find(); { "_id" : ObjectId("547e9b79f2b519cd1657b21e"), "name" : "Jonathan" } { "_id" : ObjectId("547e9b88f2b519cd1657b21f"), "name" : "Sandy" } db.test.find({name: { $in: [/Jonathan has the best queries/]} } );

I need to construct a query that would return "Jonathan" when provided the input "Jonathan has the best queries"

Upvotes: 0

Views: 60

Answers (1)

anhlc
anhlc

Reputation: 14439

This $where may do the trick, though can be very slow:

db.test.find({$where: function() {
  var mystr = '/Jonathan has the best queries/'; 
  var patt = new RegExp(this.name);
  if (patt.test(mystr)) return true;
  return false;
}})

Upvotes: 1

Related Questions