node.js - 使用 Array 进行 MongoDB 正则表达式搜索

标签 node.js mongodb mapreduce sails.js

我正在寻找一种逻辑来从数据库中的 1000 条记录中检索数据。我不能在应用程序级别做。

我有以两个双字母结尾的数据,如“ll, gg, ss, ff...”。想从数据库中检索以上述双字符结尾的单词。

我的示例数据库:

  [{
     "word": "Floss"
   }, {
    "word": "smacx"
   }, {
   "word": "fuzz"
   }, {
    "word": "grass"
   }, {
    "word": "dress"
   }, {
    "word": "puff"
   }, {
    "word": "cliff"
   }, {
    "word": "sniff"
   }, {
    "word": "chess"
   }, {
    "word": "kiss"
   }, {
    "word": "fell"
   }, {
    "word": "shell"
  }]

checkarray = ['ll','gg','ll','ss'];

关于如何在数据库级别执行此操作的任何想法。应用程序级循环变得越来越高,并且花费了更多时间,因为它有近 10 万条记录。

最佳答案

您可以 use the $in with regular expression通过创建一个新的 数组 RegExp 对象与 $in 一起使用表达式如下:

var checkarray = ['ll','gg','ll','ss'],
    regex = checkarray.map(function (k) { return new RegExp(k); });
db.collection.find({
    "word": { "$in": regex } 
})

请记住,使用 $in 对于小型数组可能相当有效,但对于大型列表则不太有效,因为它会在索引中跳过以查找匹配的文档,或者如果没有索引可使用则遍历整个集合。 p>


此外using the $in with the regular expression , 您可以使用 $regex 运算符以竖线分隔的正则表达式模式包含 checkarray,如下所示:

var checkarray = ['ll','gg','ll','ss'],
    regex = checkarray.join("|");
db.collection.find({
    "word": {
        "$regex": regex, 
        "$options": "i"
    } 
})

要匹配最后两个字符,请使用以下模式 \gg$\,即将 $ 附加到 $ 元字符所在的模式表示字符串的结尾。例如,模式 abc$ 可以匹配以下 abc, endsinabc, 123abc, ...

所以,对于你的后续问题

I need words which is ending of letters of checkArray, not in the middle or starting. CheckArray characters should be in ending letter of string. like "EGG" not "FILLED"

你可以这样做:

var checkarray = ['ll','gg','ff','ss'],
    regex = checkarray.map(function (k) { return new RegExp(k+'$'); });
db.collection.find({
    "word": { "$in": regex } 
})

要对此进行测试,请将这些示例文档填充到测试集合中:

db.test.insert([
    { "_id": 1, "word" : "well" },
    { "_id": 2, "word" : "filled" },
    { "_id": 3, "word" : "glass" },
    { "_id": 4, "word" : "blessed" }
])

以上查询将返回带有 _id1 和 3 的文档。

{ "_id" : 1, "word" : "well" }
{ "_id" : 3, "word" : "glass" }

关于node.js - 使用 Array 进行 MongoDB 正则表达式搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36623737/

相关文章:

performance - 分布式局部聚类系数算法(MapReduce/Hadoop)

Node.js sequelize 嵌入 hasMany ID

node.js - 通过(全局)shell脚本启动 Node 时如何禁用警告

node.js - MongoDB + NodeJS 的 16 个字符唯一 ID

node.js - Node JS mongodb : use global connection or local connection

hadoop - Hive 是否可以在不分区或不编辑 hive-site.xml 的情况下递归下降到子目录?

hadoop - 如何在级联中强制 reducer ?

javascript - Sequelize hasMany 关系的 getAssociation

node.js - 无需 sudo 安装 npm

node.js - 如何使用 $lookup 和 DbRef 连接 MongoDB 和 NodeJS 中的两个集合?