2014-02-12 27 views
0

嗨,大家好,我們才能做這樣的事情在MongoDB中MongoDB的COL1 + LIKE '%測試%'

COL1 + COL2 LIKE '%測試%'

COL2,因爲我有搜索測試的具有架構

collection = { "col1" : "sds" , "col2" : "est" , "col3" : ""} 
+0

是要找到「測試」在任何COL1 ** **或COL2你的問題,或者試圖連接這些值並找到字符串 –

回答

1

收集存在嘗試

db.collection.find({ $where: "/^.*test.*$/.test(this.col1 + this.col2)" }); 

在這種情況下,正則表達式/test/也應該起作用。

當然蒙戈已經做了所有文件進行全面掃描,因爲沒有選擇使用索引。

MongoDB doc $where

1

如果你想連接:

如果您嘗試來連接並仍想使用一個索引,你可能至少要找到這其中「COL1」和「COL2」的存在,因爲試圖連接不在那裏的東西最終會出現可怕的錯誤。

考慮集合,好一點的級聯將匹配測試:

{ col1: "sdst", col2: "est", col3: "abc"} 

與在$match$concat操作和使用$regex聚集:

db.test.aggregate([ 
    // Find the rows you can concatenate -- uses index 
    {$match: { col1: {$exists: true}, col2: {$exists: true}} }, 

    // Concatenate the strings and retain the original columns 
    {$project:{ 
     col1: 1, 
     col2: 1, 
     col3: 1, 
     newcol: {$concat: [ "$col1", "$col2" ]} 
    }}, 

    // Match the required strings in the concatenated result 
    {$match: { newcol: {$regex: "test", $options: "i"} } }, 

    // Restore the original document fields only  
    {$project: { col1: 1, col2: 1, col3: 1 } 
]) 

這仍然不能使用但是它比$where好一點,它會根本無法使用索引。

如果您的意思是您想在「col1」和「col2」中找到「test」,那麼很容易,只需在查詢中使用$or即可找到。

db.test.find({ $or: [ { col1: "test" }, { col2: "test" } ] }) 

或$ regex如果你必須在字符串中找到它。需要注意的是$正則表達式是不是很有效的,如果你不是從字符串開始尋找,如:「^測試」