regex - 如何使用 mongoose find 获取包含部分字符串的所有值?

我在使用 mongoose 从 MongoDB 检索数据时遇到以下问题。

这是我的架构:

const BookSchema = new Schema(
    {
        _id:Number,
        title:String,
        authors:[String],
        subjects:[String]   
    }
);

你可以看到我在对象中嵌入了 2 个数组,假设作者的内容可以是这样的:作者:[“亚历克斯弗 Gson ”,“迪迪埃德罗巴”,“克里斯蒂亚诺罗纳尔多”,“亚历克斯” ]
我想要实现的是获取数组中的所有 Alex。

到目前为止,如果它们完全匹配值,我已经能够获取这些值。但是,如果我尝试获取包含 Alex 的答案,则答案始终是 []。

我想知道的是如何使用 find() 来做到这一点,而无需执行 map-reduce 来创建 View 或集合,然后在其上应用 find()。

此处的代码适用于完全匹配

Book.find( {authors:req.query.q} , function(errs, books){
            if(errs){
                res.send(errs); 
            }

            res.json(books);
        });

我尝试了一些东西,但没有运气 {作者:{$elemMatch:req.query.q}} {作者:{$in:[req.query.q]}}

这给了我一个错误,最重要的是,在我在这里找到的另一篇文章中说效率很低。 {$where:this.authors.indexOf(req.query.q) != -1}

我也试过 {authors:{$regex:"./value/i"}}

map-reduce 工作正常,我需要使用另一种方法使其工作,看看哪个更好?

非常感谢任何帮助。我确信这很容易,但我是 NodeJS 和 Mongo 的新手,我自己无法弄清楚。

最佳答案

您几乎自己在标签中回答了这个问题。 MongoDB 有一个 $regex允许将正则表达式作为查询提交的运算符。所以你查询包含“Alex”的字符串你这样做:

Books.find(
    { "authors": { "$regex": "Alex", "$options": "i" } },
    function(err,docs) { 
    } 
);

您也可以这样做:

Books.find(
    { "authors": /Alex/i }, 
    function(err,docs) { 

    }
);

两者都是有效的,并且与您在文档中显示的正确支持的语法中尝试的方式不同。

但当然,如果您实际上是在问“如何仅针对与字符串中某处匹配 'Alex' 的结果获取 'array' 结果?”那么这就有点不一样了。

多个一个数组元素的复杂匹配是aggregation framework的域(或者可能是 mapReduce,但这要慢得多),您需要“过滤”数组内容。

你的开始大致相同。这里的关键是$unwind对数组内容进行“反规范化”,以便能够作为单个文档正确“过滤”。然后用“匹配”的文档重新构造数组。

Books.aggregate(
    [
        // Match first to reduce documents to those where the array contains the match
        { "$match": {
            "authors": { "$regex": "Alex", "$options": i }
        }},

        // Unwind to "de-normalize" the document per array element
        { "$unwind": "$authors" },

        // Now filter those document for the elements that match
        { "$match": {
            "authors": { "$regex": "Alex", "$options": i }
        }},

        // Group back as an array with only the matching elements
        { "$group": {
            "_id": "$_id",
            "title": { "$first": "$title" },
            "authors": { "$push": "$authors" },
            "subjects": { "$first": "$subjects" }
        }}
    ],
    function(err,results) {

    }
)

https://stackoverflow.com/questions/26814456/

相关文章:

mongodb - 如何将 mongodb 数据库转移到另一台看不到第一个的机器上

mongodb - 使用 apt-get 安装 mongodb-10gen 失败

mongodb - 复制/克隆 mongodb 数据库及其数据

mongodb - 异常 : can't convert from BSON type EOO to

mongodb - 将 PouchDB 与 MongoDB 一起使用

php - 找不到类 'MongoClient'

javascript - MongoDB mongoose 弃用警告

javascript - 如何在 MongoDB 中对集合记录中的数组进行排序?

mongodb - 如何使用 nodejs 流式传输 MongoDB 查询结果?

mongodb - 更新 Mongodb 中的嵌入文档属性