在 MongoDB 中搜索 [英] Searching in MongoDB

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

问题描述

假设您需要在 MongoDB 中实现搜索.您的文档集合如下所示:

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"}

现在您要实现不区分大小写的搜索,该搜索将返回包含搜索词的所有文档.例如,如果您搜索文本",它将返回两个文档.如果你搜索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.

我知道你可以像这样使用 $regex 来做到这一点:

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

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

SEARCH_TERM 是我们要查找的术语.

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?

推荐答案

也许全文搜索就是你的答案http://docs.mongodb.org/manual/core/index-text/http://docs.mongodb.org/manual/reference/operator/query/文字/

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" } )

以下代码搜索包含词 Thisanother 但不包含词 hehe 的评论:

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天全站免登陆