如何使用 mongoose find 获取包含部分字符串的所有值? [英] How to get all the values that contains part of a string using mongoose find?

查看:19
本文介绍了如何使用 mongoose find 获取包含部分字符串的所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following problem retrieving data from MongoDB using mongoose.

这是我的架构:

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

如您所见,我在对象中嵌入了 2 个数组,假设作者的内容可以是这样的:作者:[亚历克斯弗格森",迪迪埃德罗巴",克里斯蒂亚诺罗纳尔多",亚历克斯"]
我想要实现的是获取数组中的所有 Alex.

as you can see i have 2 arrays embedded in the object, let's say the content of the authors can be something like this: authors:["Alex Ferguson", "Didier Drogba", "Cristiano Ronaldo", "Alex"]
what I'm trying to achieve is get all the Alex in the array.

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

So far, I've been able to get the values if they match the value completely. However if I try to get the ones containing Alex the answer is always [].

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

What I want to know is how I can do this using find() without performing a map-reduce to create a view or a collection and then applying find() over that.

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

The code here works for exact matches

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

I tried some things but no luck {authors:{$elemMatch:req.query.q}} {authors:{$in:[req.query.q]}}

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

This one gives me an error and on top of that says is very inefficient in another post I found here. {$where:this.authors.indexOf(req.query.q) != -1}

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

and I also tried {authors:{$regex:"./value/i"}}

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

The map-reduce works fine, I need to make it work using the other approach to see which one is better?

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

Any help is greatly appreciated. I'm sure this is easy, but I'm new with NodeJS and Mongo and I haven't been able to figure it out on my own.

推荐答案

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

You almost answered this yourself in your tags. MongoDB has a $regex operator which allows a regular expression to be submitted as a query. So you query for strings containing "Alex" you do this:

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

您也可以这样做:

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

    }
);

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

Both are valid and different to how you tried in the correct supported syntax as shown in the documentation.

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

But of course if you are actually asking "how to get the 'array' results only for those that match 'Alex' somewhere in the string?" then this is a bit different.

一个数组元素的复杂匹配是 聚合框架(或者可能是 mapReduce,但速度要慢得多),您需要在其中过滤"数组内容.

Complex matching for more than one array element is the domain of the aggregation framework ( or possibly mapReduce, but that is much slower ), where you need to "filter" the array content.

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

You start of much the same. The key here is to $unwind to "de-normalize" the array content in order to be alble to "filter" properly as individual documents. Then re-construct the array with the "matching" documents.

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) {

    }
)

这篇关于如何使用 mongoose find 获取包含部分字符串的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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