2012-04-14 133 views
5

我似乎無法在google上找到答案,也沒有貓鼬網站,所以我在這裏問。如果可能的話,我如何在文檔中搜索部分匹配的字符串。查找匹配的部分字符串

例如:

在用戶採集:

{ name: "Louis", location: "Paris, France" }, 
{ name: "Bill", location: "Paris, Illinoid" }, 
{ name: "Stephen", location: "Toronto, Ontario" } 

貓鼬功能:

searchForCity("Paris"); 

其結果將是從具有 「巴黎」 用戶採集文檔的列表中位置字符串。例如:

[ 
    { name: "Louis", location: "Paris, France" }, 
    { name: "Homer", location: "Paris, Illinois" } 
] 
+0

Hiya希望這有助於:http://www.mongodb.org/display/DOCS/Advanced+Queries尋找.find有一個很好的,歡呼! – 2012-04-14 19:52:06

回答

16

你可以使用一個regex

Query#regexQuery#$regex

指定$regex操作。

query.regex('name.first', /^a/i) 

因此,像這樣:

User.where('location').$regex(/Paris/); 
User.where('location').$regex(/paris/i); // Case insensitive version 

請記住,正則表達式查詢可以是非常昂貴的,因爲MongoDB的必須針對每一單location運行正則表達式。如果你可以在開始處固定你的正則表達式:

User.where('location').$regex(/^Paris/); 

然後你可以索引位置,MongoDB將使用該索引。

+2

完美工作,不得不添加:var expression = new RegExp(word,「i」);, were word =「Paris」;這是我可以在其中包含變量。 – guiomie 2012-04-14 23:53:26

+0

有沒有貓鼬解決方案? – chovy 2015-02-11 06:33:02

+0

@chovy嗯,答案*的哪一部分不是*貓鼬解決方案? – 2015-02-11 07:15:46