Mongodb正则表达式搜索,但不';我不能归还所有文件
我试图在下面的收藏中搜索一个字符串Mongodb正则表达式搜索,但不';我不能归还所有文件,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我试图在下面的收藏中搜索一个字符串 { question: "What is your least favorite thing about living in the USA?", description: "aaaa" }, { question: "What is the saddest thing a casino dealer has seen at their table?", descrip
{
question: "What is your least favorite thing about living in the USA?",
description: "aaaa"
},
{
question: "What is the saddest thing a casino dealer has seen at their table?",
description: "bbbb"
}
我可以通过使用
db.questions.aggregate(
[
{ $match: { question_title: { $regex: 'what', $options: "i" } }
]
)
我收到了两份文件。但是,当我使用关键字
'what USA'
我没有收到任何结果。我的预期结果是
"What is your least favorite thing about living in the USA?"
你能给我推荐一个我可以使用的正则表达式吗?这样,如果我的任何关键字与问题文档匹配,我都会得到一个结果。你可以使用这样的方法:
db.questions.aggregate([
{ $match: { question: { $regex: '(?i)(:s|usa|what)', $options: "i" } } }
])
这是不区分大小写的(?i)
匹配,当前查找usa
或what
您可以您可以使用以下内容:
db.questions.aggregate([
{ $match: { question: { $regex: '(?i)(:s|usa|what)', $options: "i" } } }
])
这是不区分大小写的(?i)
匹配,当前查找usa
或what
您可以动态正则表达式:
1.此正则表达式与“ua what”的返回结果不匹配:
var searchString = 'usa what';
var regexStr = '(?i)(:s|' + searchString.split(' ').join('|')+')';
db.getCollection('searchQuestion').aggregate(
[
{ $match: { question: { $regex: regexStr, $options: "i" } } },
]
);
2.查找完全匹配的单词
例如:
var searchStringg = 'usa what';
var regexStrr = '\\b' + searchStringg.split(' ').join('\\b|\\b')+'\\b';
db.getCollection('searchQuestion').aggregate(
[
{ $match: { question: { $regex: regexStrr, $options: "i" } } },
]
)
动态正则表达式:
1.此正则表达式与“ua what”的返回结果不匹配:
var searchString = 'usa what';
var regexStr = '(?i)(:s|' + searchString.split(' ').join('|')+')';
db.getCollection('searchQuestion').aggregate(
[
{ $match: { question: { $regex: regexStr, $options: "i" } } },
]
);
2.查找完全匹配的单词
例如:
var searchStringg = 'usa what';
var regexStrr = '\\b' + searchStringg.split(' ').join('\\b|\\b')+'\\b';
db.getCollection('searchQuestion').aggregate(
[
{ $match: { question: { $regex: regexStrr, $options: "i" } } },
]
)
对于关键字,假设我在nodeJS中有一个值const keyword='test',我可以像这样输入$regex:'(?I)(:s | keyword |)',因为关键字是来自useryes的输入,这就是想法。。。您将得到
{$regex:'(?i)(:s | test)'),$options:“i”}
在NodeJS中,我似乎无法使用用户的输入。如果我输入$regex:“(?I)(:s | usa | what)”,它确实有效,但是如果我输入关键字变量,比如var keyword=userInput和$regex:“(?I)(:s | userInput)”,mongoDB无法识别。您知道如何处理此问题吗?$regex:'(?i)(:s |'+userInput+)'
或者您是否可以使用模板文字$regex:(?i)(:s |${userInput})
。基本上你需要把字符串和变量连在一起明白了吗!非常感谢!对于关键字,假设我在nodeJS中有一个值const keyword='test',我可以像这样输入$regex:'(?I)(:s | keyword |)',因为关键字是来自useryes的输入,这就是想法。。。您将得到{$regex:'(?i)(:s | test)'),$options:“i”}
在NodeJS中,我似乎无法使用用户的输入。如果我输入$regex:“(?I)(:s | usa | what)”,它确实有效,但是如果我输入关键字变量,比如var keyword=userInput和$regex:“(?I)(:s | userInput)”,mongoDB无法识别。您知道如何处理此问题吗?$regex:'(?i)(:s |'+userInput+)'
或者您是否可以使用模板文字$regex:(?i)(:s |${userInput})
。基本上你需要把字符串和变量连在一起明白了吗!非常感谢!既然我们有$options:“i”,我们还需要(?i)吗既然我们有$options:“i”,我们还需要(?i)吗