Mongodb Nodejs 正则表达式查询 [英] Mongodb Nodejs Regex Query

查看:71
本文介绍了Mongodb Nodejs 正则表达式查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用模块mongodb"从节点 js API 查询 mongodb.我正在尝试通过搜索查询来搜索联系人文档.相同的选择器如下:

I am using the module "mongodb" to query mongodb from node js APIs. I am trying to search contacts document by a search query. The selector for the same is as below:

selector['users.name'] = {$regex: new RegExp(params.query), $options:"i"}

考虑到用户的名字是Sagar Gopale"并且搜索查询是sagar"甚至gopale",那么上面的工作正常并正确返回结果.但是,如果我将搜索查询输入为sagar gopale",它会返回空结果.有人可以为我提供解决方案,以便我可以输入包含空格的搜索查询吗?

Consider the name of the user is "Sagar Gopale" and the search query is "sagar" or even "gopale" then the above works fine and returns results properly. But if I input search query as "sagar gopale" it returns empty result. Can someone provide me a solution so that I can input the search query including the space?

提前致谢.

推荐答案

实际上,如果您坚持使用 regexp 方法,在这里会遇到很多困难,我建议您创建一个 text 索引:

Actualy you will have many difficulties here if you stick with the regexp aproach, I suggest you to create a text index:

collection.createIndex({"users.name" : "text"});

然后你什么时候会搜索:

And then when you will search:

db.collection('users').find({
  $text: {
    $search: params.query,
    $caseSensitive: false,
  }
});

这样,当您使用Sagar"、sagar"、sagar gopa"、gopale sagar"以及这 2 种的多种组合时,您将得到结果.

In this way you will get the result when you use "Sagar", "sagar", "sagar gopa", "gopale sagar", and many combinations of those 2.

如果您有自动完成功能,或者客户端不知道确切的名称,则此方法非常有效.Mongo 处理了会匹配字母的强文本搜索算法,即使它们的顺序不正确.

This aproach works very nicely if you have an autocomplete, or the client doesn't know exactly the name. Mongo dispose of strong text search algorithms that will match letters, even if they are not in proper order.

这篇关于Mongodb Nodejs 正则表达式查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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