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" }
]
(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.
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.)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With