Regex 如何使用mongoose find获取包含字符串一部分的所有值?
我在使用mongoose从MongoDB检索数据时遇到以下问题 这是我的模式:Regex 如何使用mongoose find获取包含字符串一部分的所有值?,regex,node.js,mongodb,mongodb-query,aggregation-framework,Regex,Node.js,Mongodb,Mongodb Query,Aggregation Framework,我在使用mongoose从MongoDB检索数据时遇到以下问题 这是我的模式: const BookSchema = new Schema( { _id:Number, title:String, authors:[String], subjects:[String] } ); 如您所见,我在对象中嵌入了2个数组,假设作者的内容可以是这样的:作者:[“亚历克斯·弗格森”、“迪迪埃·德罗巴”、“克里斯蒂亚诺·罗
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是新手,我自己还没能弄清楚。你几乎自己在标签上回答了这个问题。MongoDB有一个运算符,允许将正则表达式作为查询提交。因此,您可以查询包含“Alex”的字符串,您可以执行以下操作:
Books.find(
{ "authors": { "$regex": "Alex", "$options": "i" } },
function(err,docs) {
}
);
您也可以这样做:
Books.find(
{ "authors": /Alex/i },
function(err,docs) {
}
);
两者都是有效的,并且与您在文档中所示的正确支持语法中的尝试方式不同
当然,如果你问“如何只对字符串中某个地方与‘Alex’匹配的字符串获取‘array’结果?”那么这就有点不同了
多个数组元素的复杂匹配是的域(或者可能是mapReduce,但速度要慢得多),您需要在其中“过滤”数组内容
你开始的时候也差不多。这里的关键是“反规范化”数组内容,以便能够作为单个文档进行适当的“过滤”。然后用“匹配”文档重新构造数组
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) {
}
)
找到标题包含以下内容的帖子:
cool
,并且不区分大小写
匹配:(Very cool
havecool
)
const s = 'cool'
const regex = new RegExp(s, 'i') // i for case insensitive
Posts.find({title: {$regex: regex}})