gkd
gkd

Reputation: 863

mogodb RegEx returns all records when one letter in pattern

I have a collection (table in RDBMS) in mongodb that contains names of mail receivers.

A Name may contain normal english characters or Japanese characters or combination of both.

I am using RegExp to find names which match with pattern I am passing, below is code

db.user_logs.find({ "recipientName": new RegExp(".*漢字*", "i") })

This returns all records which contains "漢字" at any position within name

but when i use

db.user_logs.find({ "recipientName": new RegExp(".*漢*", "i") })

it returns all records whether it contains "漢" or not.

my requirement is i need only those records in which "漢" exists at any position

same is happening for english characters.

Upvotes: 1

Views: 777

Answers (2)

nhahtdh
nhahtdh

Reputation: 56809

To check that certain sequence of character1 appear in the name, the regex can be as simple as:

db.user_logs.find({ "recipientName": new RegExp("漢字", "i") })
db.user_logs.find({ "recipientName": new RegExp("漢", "i" })

1 If the string contains meta-characters (characters with special meaning in regex), you need to escape them.

The i flag is redundant for Chinese and Japanese characters, but I leave it there in case you need to use Latin search string.

There is also the option of using literal regex if the regex is fixed:

db.user_logs.find({ "recipientName": /漢字/ })
db.user_logs.find({ "recipientName": /漢/ })

i flag removed here, since you don't need it.

Upvotes: 5

user230910
user230910

Reputation: 2372

I could be wrong, but I think you should change the last * to a +

* 

Means 0 or more matches, so it's optional.

db.user_logs.find({ "recipientName": new RegExp(".*漢.*", "i") })
           or
db.user_logs.find({ "recipientName": new RegExp(".*漢+", "i") })

Upvotes: 1

Related Questions