我有一個貓鼬模式:
const userSchema = new mongoose.Schema({
keywords: [{ "type": String, "enum": ["yup", "nope"] }],
})
在這里,我有一個用戶有一組關鍵字,我想在我的資料庫中找到與該特定用戶最相似的一組關鍵字的記錄。
例如,如果用戶["yup" "nope"]將關鍵字作為關鍵字,我想查找關鍵字陣列中具有“yup”或“nope”或兩者的用戶的所有記錄。這只是一個例子,實際上,用戶將有更多的關鍵字可供選擇。
我怎樣才能使用貓鼬做到這一點?
我正在考慮對陣列中的值進行單熱編碼,并且可以將具有最匹配 1 的記錄添加到另一個表“最相似的值表或其他東西”中,該表為每個用戶維護此串列,并將用戶作為外鍵. 但是我還沒有能夠為此提出一種有效和/或有效的演算法。
uj5u.com熱心網友回復:
在我看來,最好的方法是定期表達。我為您撰寫了一個示例函式,如何使用 mongoose 在 MongoDB 中搜索和過濾資料。例如,讓我們通過 lastName 示例搜索客戶的開始、結束、包含字串“yup”。請注意,使用正則運算式進行搜索是區分大小寫的默認值。如果在正則運算式后添加“i”,它將不區分大小寫。
async function getCustomers() {
const customers = await Customer
//case search lastName whitch starts with "yup" - case sensitive
.find({lastName: /^yup/})
//or case search lastName whitch ends with "yup" - case insensitive
.find({lastName: /yup$/i })
//or case search lastName whitch contains "yup" in any part
.find({lastName: /.*yup.*/ })
.limit(20) //get top 20 results
.sort({lastName: 1}) // sort by lastName
console.log(customers)}
//searching in array
const customerList = ['Smith', 'Jackson'];
async function getCustomers(arr) {
return await Customer
.find({lastName: {$in: arr}})
.limit(20) //get top 20 results
.sort({lastName: 1}) // sort by lastName
}
getCustomers(customerList);
有關更多資訊,請檢查檔案:https ://docs.mongodb.com/manual/reference/operator/query/regex/
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/396564.html
