Fabio Ebner
Fabio Ebner

Reputation: 2783

Mongo search regex ignore puntuation

It`s possible to create one regex in mongo search to ignore puntuation ?

I have in my collection something like

123.456.789-01

or

33.018.843/09881-20

So if I look for some 123456 (I want to find the first or more) and if I found for 8430 (I need to find the second or more)

I want to ignore the puntuation and when that string are.

tks

Upvotes: 1

Views: 424

Answers (2)

satish chennupati
satish chennupati

Reputation: 2650

Yes, you can. Are you aware of the $options operator that goes with $regex?

$options: "x" will help you overcome this.

Upvotes: 1

felipsmartins
felipsmartins

Reputation: 13549

Well, I'm not sure it is possible via regex. However, there's a workaround, look this:

given the following colletion:

> db.teste.find() 
{
    "_id": ObjectId("57f65bc8b9b3f8a0acacc0c1"),
    "num": "33.018.843/09]881-20"
} 
{
    "_id": ObjectId("57f65bcbb9b3f8a0acacc0c2"),
    "num": "123.456.789-01"
}

So:

db.teste.find().map(function(doc) {
    var str = doc.num.replace(/[./\-]/g, "");
    if (str.indexOf("8430") > -1) return (doc);
}).filter(function(e, i) {
    if (e) return e;
});

I don't know what you are doing neither what are your needs but I hope it be helpful.

Upvotes: 1

Related Questions