【问题标题】:How to get all the values that contains part of a string using mongoose find?如何使用 mongoose find 获取包含部分字符串的所有值?
【发布时间】:2015-01-05 00:35:33
【问题描述】:

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

这是我的架构:

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

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

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

我想知道的是如何使用 find() 来做到这一点,而无需执行 map-reduce 来创建视图或集合,然后在其上应用 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 的新手,我自己无法弄清楚。

【问题讨论】:

    标签: regex node.js mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您几乎自己在标签中回答了这个问题。 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) {
    
        }
    )
    

    【讨论】:

      【解决方案2】:

      查找标题包含:coolcase insensitive 的帖子匹配:(Very Cool 也有 cool

      const s = 'cool'
      const regex = new RegExp(s, 'i') // i for case insensitive
      Posts.find({title: {$regex: regex}})
      

      【讨论】:

        【解决方案3】:

        使用 mongoose 和 $regex 进行实时搜索

        以下是获取书籍以搜索文本开头的查询。

        var result = await Books.find({ 'authors': { $regex: '^' + search_text, $options: 'i' } }).exec();
        

        【讨论】:

          猜你喜欢
          • 2020-09-24
          • 2020-06-06
          • 1970-01-01
          • 2023-03-28
          • 2020-10-03
          • 2021-12-23
          • 1970-01-01
          • 2011-05-30
          • 1970-01-01
          相关资源
          最近更新 更多