2014-10-20 100 views
2

想象一下,您需要在MongoDB中实现搜索。 你有看起来像这样的文件集:在MongoDB中搜索

{text: "This is some Text } 
{text: "this is another text hehe"} 

现在要实现不区分大小写的搜索,将返回所有包含搜索词的文件。例如,如果您搜索“文本”,它将返回两个文档。如果您搜索“嘿嘿”,它将只返回第二个文档。

我知道你可以做到这一点使用正则表达式$像这样:

db.comments.find({text: {$regex: /.*SEARCH_TERM.*/i}}); 

哪里SEARCH_TERM是我们正在寻找的一个术语。

我想知道是否有更好的方法来做到这一点,因为通过正则表达式搜索似乎是一个坏主意。没有索引或任何这种方式。

我的想法是,你可以以某种记号化文档中的文本,所以你有这样的文件:

{text: ["This", "is", "some", "Text"]} 
{text: ["this", "is", "another", "text", "hehe"]} 

,然后索引这些阵列。有没有更好的方法来做到这一点?

回答

1

可能会很有趣做的Map Reduce:

mapper=function(){ 
    var words=this.text.match(/\S+\s*/g); 
    for (w in words){ 
     emit(this._id, {'words':words}) 
    } 
} 

reducer=function(k,v){return {'words':this[0].words}} 

这应该让你的话的集合分离出来。有可能通过聚合做到这一点。