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" }
]
You could use a regex for that:
So something like this:
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:then you can index the location and MongoDB will use that index.