2013-04-21 41 views
0

我有一個集合,看起來像這樣:映射/減少正則表達式聚合?

{ "_id" : ObjectId("51745ec04fdde5d77e4c5ed3"), "pattern" : "^a$" } 
{ "_id" : ObjectId("51745ecb4fdde5d77e4c5ed4"), "pattern" : "^b$" } 
{ "_id" : ObjectId("51745ece4fdde5d77e4c5ed5"), "pattern" : "^c$" } 

我基本上是想看看如果單個輸入值的集合中定義的任何正則表達式匹配。我有點新的Map/Reduce功能,但我會寫這在JavaScript中串行像這樣:

function matches(input, collection) { 
    for (var i = 0; i < collection; i++) { 
     if (input.match(collection[i].pattern)) 
      return true; 
    } 

    return false; 
} 

如果我是並行寫這篇文章,它會歸結到這一點:

function matches(input, item) { 
    return input.match(item.pattern); 
} 

我會再減少下來,看是否存在結果數組中true

我怎樣寫這個作爲的map/reduce方案MongoDB的,以找出是否輸入值的集合中的任何正則表達式匹配?

回答

1

我不知道爲什麼你需要在這裏映射/減少。看來你可以做類似這樣(在蒙戈外殼)一個簡單的迭代:

> var input="a"; 
> db.collection.find({},{_id:0,pattern:1}).forEach(function(d) { 
    if (input.match(d["pattern"])) 
     print (tojson(d)+" matches"); 
}) 
{ "pattern" : "^a$" } matches 
> 
+0

我想執行操作並得到一個簡單的'真'或'FALSE'從MongoDB的回來。使用上面概述的方法可以這樣做嗎? – 2013-04-23 04:44:49

+0

用print(true)替換print(tojson ...) – 2013-04-23 05:18:03

+0

或者把find放入一個函數裏面然後返回true,否則返回false。 – 2013-04-23 05:25:05