Skip to content

Instantly share code, notes, and snippets.

@ctrlaltdylan
Last active April 3, 2021 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctrlaltdylan/99941175d31fc4670e986e03c869dd87 to your computer and use it in GitHub Desktop.
Save ctrlaltdylan/99941175d31fc4670e986e03c869dd87 to your computer and use it in GitHub Desktop.
Mongo Text Searching (with partial matching)
async function createTextSearchIndex(db) {
db.collection("customers").createIndex({
firstName: "text",
lastName: "text",
email: "text",
phone: "text"
});
}
async function createRegexSearchIndex(db) {
db.collection("customers").createIndex({
firstName: 1,
lastName: 1,
email: 1,
phone: 1
});
}
const searchTerm = req.query.searchTerm;
const customers = await db.collection('customers).find({
$or: [
// the first step is to see if the exact word matches, if not then go onto the regex based search
{
$text: {
$search: searchTerm,
}
},
{ firstName: new RegExp(searchTerm, "i") },
{ lastName: new RegExp(searchTerm, "i") },
{ email: new RegExp(searchTerm, "i") },
{ phone: new RegExp(searchTerm, "i") }
]
}).toArray();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment