2013-05-15 83 views
12

我想在文檔中搜索具有特殊字符的值,如" $/. @ > "在MongoDB文檔中搜索帶有特殊字符的字符串

讓我們考慮,我一直用的myKey像值"test$australia", "test$austria", "test$belgium", "green.africa".

我想與'.*$aus.*',

例如搜索值,

db.myCollection.find({ myKey : /.*$aus.*/i }); 

OR

db.myCollection.find({ myKey : { '$regex' : '.*$aus.*','$options' : 'i' }); 

以上查詢不工作,浩我應該形成查詢嗎? 我正在使用MongoDB 2.4.1。

回答

12

你要逃避$\

db.myCollection.find({ myKey : /.*\$aus.*/i }); 
// OR 
db.myCollection.find({myKey: { $regex: '.*\\$aus.*', $options: 'i'}}) 
+0

請問您可以刪除在控制檯中不需要的qr操作符..我也編輯了問題。它確實有效。 – dex

+0

另外我怎樣才能達到與REGEX選項相同。 – dex

+1

您必須在mongo json查詢中的正則表達式字符串中加上反斜槓:'db.myCollection.find({myKey:{$ regex:'。* \\ $ aus。*',$ options:'i'}} )' –

3
db.test.insert({word: 'hai('}); 
db.test.insert({word: 'jana'}); 

輸出是這樣的:

{ "_id" : ObjectId("56f27fb71d843581261433c6"), "word" : "hai(" } 
{ "_id" : ObjectId("56f27ffe1d843581261433c8"), "word" : "jana" } 

注:想獨自特殊字符行,以便

db.test.find({word:{$regex:"\\("}}); 

輸出是這樣的:

{ "_id" : ObjectId("56f27fb71d843581261433c6"), "word" : "hai(" } 
相關問題