Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find matching partial string

I can't seem to find an answer on google, nor the mongoose website, so I am asking here. If it is possible, how can I search for a partially matching string in a document.

ex:

In a user collection:

{ name: "Louis", location: "Paris, France" },
{ name: "Bill", location: "Paris, Illinoid" },
{ name: "Stephen", location: "Toronto, Ontario" }

mongoose function:

searchForCity("Paris");

The result would be a list of documents from the User collection having "Paris" in the location String. ex:

[
    { name: "Louis", location: "Paris, France" },
    { name: "Homer", location: "Paris, Illinois" }
]
like image 939
guiomie Avatar asked Apr 14 '12 19:04

guiomie


People also ask

How do you match partial strings?

(A partial match occurs if the whole of the element of x matches the beginning of the element of table .) Finally, all remaining elements of x are regarded as unmatched. In addition, an empty string can match nothing, not even an exact match to an empty string.

How do you calculate a partial match?

If you just want to find which name is partial match the given name, you also can use this formula =INDEX($E$2:$E$14,MATCH($K$1&"*",E2:E14,0)). (E2:E14 is the column list you want to lookup from, k1 is the given name, you can change as you need.)

How do you find the partial string match in Python?

Use the in operator for partial matches, i.e., whether one string contains the other string. x in y returns True if x is contained in y ( x is a substring of y ), and False if it is not. If each character of x is contained in y discretely, False is returned.


1 Answers

You could use a regex for that:

Query#regex, Query#$regex

Specifies the $regex operator.

query.regex('name.first', /^a/i)

So something like this:

User.where('location').$regex(/Paris/);
User.where('location').$regex(/paris/i); // Case insensitive version

Keep in mind that regex queries can be very expensive as MongoDB will have to run the regex against every single location. If you can anchor your regexes at the beginning:

User.where('location').$regex(/^Paris/);

then you can index the location and MongoDB will use that index.

like image 176
mu is too short Avatar answered Sep 22 '22 19:09

mu is too short