我想在使用MongoDB的Node JS中的項目中創建高級搜索。我在數據庫中創建了一個搜索關鍵字段。用戶可以在文本框中輸入任何單詞,並且我希望在字符串中匹配並獲取結果。低於我的數據庫結構和代碼。我的代碼工作只匹配所有字符串中不搜索的字符串的第一個字。在節點js中搜索字符串mongodb中的任何詞
DB :
{
"_id": ObjectId("001"),
"searchkey": "Test Product Test Product T-shirt Half sleeves Adidas"
}
{
"_id": ObjectId("123"),
"searchkey": "boy test Product Test Product T-shirt Half sleeves Nike"
}
{
"_id": ObjectId("456"),
"searchkey": "girl test Product Summer Product T-shirt full sleeves Adidas"
}
{
"_id": ObjectId("789"),
"searchkey": "any product any Product any Product T-shirt full sleeves Adidas"
}
{
"_id": ObjectId("1010"),
"searchkey": "woodland Product woodland Product T-shirt Half sleeves woodland"
}
{
"_id": ObjectId("1212"),
"searchkey": "Summer Product Test Product T-shirt Half sleeves Adidas"
}
My Query :
Collection.find({searchkey : {$regex: new RegExp('^' + search.toLowerCase(), 'i')},searchkey : {$regex: new RegExp('^' + search.toUpperCase(), 'i')},is_active:true},function(error,fetchSearch){
console.log(fetchSearch);
});
如果我搜索test or TEST
它會給我只有一個結果是id爲001,結果沒有從所有的字符串相匹配的休息。
我要像如果我搜索summer
或Summer
它會給我456 and 1212
_id數據。
現在意味着我的查詢像下面 –
Collection.find({searchkey {$ regex:new RegExp('。*'+ search.toLowerCase()+'。*','i')},searchkey:{$ regex:new RegExp('。*'+ search.toUpperCase()+ '。*','i')},is_active:true},function(error,fetchSearch){console.log(fetchSearch); }); –
謝謝先生(弓) –