2017-01-03 17 views
1

我想執行一個標籤搜索,它必須對標籤關鍵字不區分大小寫。我需要一個關鍵字搜索以及如何爲多個關鍵字進行搜索。但問題是,當我用以下查詢進行搜索時,我一無所獲。我是NodeJs和MongoDb的新手,如果查詢中有任何錯誤,請糾正我的錯誤。不區分大小寫在數組中的mongodb和nodejs中搜索

標籤可以是'tag1'或'TAG1'或'taG1'。

爲我用單標記關鍵字搜索(我沒有得到任何結果):

db.somecollection.find({'Tags':{'TagText': new RegExp('Tag5',"i")}, 'Status':'active'}) 

多個標籤關鍵字搜索(需要作出這種不區分大小寫太:()

db.somecollection.find({'Tags':{'TagText': {"$in": ['Tag3','Tag5', 'Tag16']}}, 'Status':'active'}) 

的記錄在DB中設置:

{ 
    "results": { 
     "products": [ 
      { 
       "_id": "5858cc242dadb72409000029", 
       "Permalink": "some-permalink-1", 
       "Tags": [ 
         {"TagText":"Tag1"}, 
         {"TagText":"Tag2"}, 
         {"TagText":"Tag3"}, 
         {"TagText":"Tag4"}, 
         {"TagText":"Tag5"} 
        ], 
       "Viewcount": 3791 
      }, 
      { 
       "_id": "58523cc212dadb72409000029", 
       "Permalink": "some-permalink-2", 
       "Tags": [ 
         {"TagText":"Tag8"}, 
         {"TagText":"Tag2"}, 
         {"TagText":"Tag1"}, 
         {"TagText":"Tag7"}, 
         {"TagText":"Tag2"} 
        ], 
       "Viewcount": 1003 
      }, 
      { 
       "_id": "5858cc242dadb11839084523", 
       "Permalink": "some-permalink-3", 
       "Tags": [ 
         {"TagText":"Tag11"}, 
         {"TagText":"Tag3"}, 
         {"TagText":"Tag1"}, 
         {"TagText":"Tag6"}, 
         {"TagText":"Tag18"} 
        ], 
       "Viewcount": 2608 
      }, 
      { 
       "_id": "5850cc242dadb11009000029", 
       "Permalink": "some-permalink-4", 
       "Tags": [ 
         {"TagText":"Tag14"}, 
         {"TagText":"Tag12"}, 
         {"TagText":"Tag4"}, 
         {"TagText":"Tag5"}, 
         {"TagText":"Tag7"} 
        ], 
       "Viewcount": 6202 
      }, 

     ], 
     "count": 4 
    } 
} 

回答

0

創建要在搜索領域的文本索引。 (默認爲不區分大小寫)

db.somecollection.createIndex({ "Tags.TagText": "text" }) 

對於更多的選擇,在$搜索搜索內容組合https://docs.mongodb.com/v3.2/core/index-text/#index-feature-text

。利用$文本操作。

更多選項,https://docs.mongodb.com/v3.2/reference/operator/query/text/#op._S_text

搜索與單個術語

db.somecollection.find({$text: { $search: "Tag3"}}); 

搜索與多個搜索字詞

db.somecollection.find({$text: { $search: "Tag3 Tag5 Tag16"}}); 

更新:

看起來你正在尋找不區分大小寫正則表達式很容易實現的平等。你會不需要文本搜索。刪除文本搜索索引。

搜索與單個術語

db.somecollection.find({'Tags.TagText': {$regex: /^Tag3$/i}}).pretty(); 

搜索與多個搜索字詞

db.somecollection.find({'Tags.TagText': {$in: [/^Tag11$/i, /^Tag6$/i]}}).pretty(); 
+0

非常感謝你薩加爾....它工作正常,我,非常感謝。 –

+0

嗨薩加爾你能告訴我一件事,這可以確切地搜索標籤。我的意思是,搜索標籤「最新的護膚品適合你的年齡」與帶有「護膚品」標籤的產品相匹配。它不應該發生。只有當我使用'Skincare'標籤進行搜索時,那麼這款產品應該會來......您能幫忙嗎?在此先感謝 –

+0

已添加更新到答案。對不明白你的要求很抱歉。看一看,讓我知道。 – Veeram