Last active
April 3, 2021 15:19
-
-
Save ctrlaltdylan/99941175d31fc4670e986e03c869dd87 to your computer and use it in GitHub Desktop.
Mongo Text Searching (with partial matching)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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