在MongoDB中搜索 [英] Searching in MongoDB

查看:88
本文介绍了在MongoDB中搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你需要在MongoDB中实现一个搜索。
您拥有如下所示的文档集合:

  {text:这是一些文本} 
{text:this is another text hehe}

现在你想实现一个不区分大小写的搜索返回所有包含搜索词的文档,例如,如果搜索text,它将返回两个文档,如果搜索hehe,则只返回第二个文档。 b

我知道你可以用$ regex这样做:

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

其中SEARCH_TERM是一个我们正在寻找的术语。



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

我的想法是,你可以以某种方式标记文档中的文本,所以你会有像这样的文件:

  {text:[This, 是,一些,文本]} 
{text:[this,is,another,text,hehe]}

然后索引这些数组。有没有更好的方法来做到这一点? 可能全文搜索是您的答案
http://docs.mongodb.org/manual/core/index-text/
http://docs.mongodb.org/manual/reference/运算符/查询/文本/



这些引用的代码片段:

  1  -  db.comments.ensureIndex({comments:text})

以下代码搜索包含 This 另一个但不包含术语 hehe 的注释:

  2- db.comments.find({$ text:{$ search:This another -hehe}})


Imagine you need to implement a search in MongoDB. You have collection of documents that look like this:

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

Now you want to implement a case insensitive search that would return all the documents that contain search term. For example, if you search for "text", it would return both documents. If you search for "hehe", it would return only second document.

I know you can do this using $regex like this:

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

Where SEARCH_TERM is a term we're looking for.

I'm wondering if there is a better way to do this because searching via regex seems like a bad idea. There is no indexing or anything this way.

My idea is that you could somehow tokenize that text in documents, so you would have documents like this:

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

and then index these arrays. Is there any better way to do this?

解决方案

Maybe the full-text-search is your answer http://docs.mongodb.org/manual/core/index-text/ http://docs.mongodb.org/manual/reference/operator/query/text/

Code snippets from these references:

1 - db.comments.ensureIndex( { comments: "text" } )

The following code searches for comments that contain the words This or another but do not contain the term hehe:

2- db.comments.find( { $text: { $search: "This another -hehe" } } )

这篇关于在MongoDB中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆